I;m new on Vuejs and I'm currently working with composition API so I have an array like this:
const tabs = ref([
{
id: 1,
pdf: 'name1',
...
},
{
id: 2,
pdf: 'name2',
...
},
{
id: 3,
pdf: 'name3',
...
},
])
Then I have a div like this:
<div
v-for="tab in tabs"
:key="tab.name"
:href="tab.href"
class="px-12 pt-8 flex flex-col"
:class="[tab.current || 'hidden']"
@click="changeTab(tab)"
>
<div v-if="pdf != ''">
<div class="pt-4 font-bold underline">
<a :href="pdfSrc" target="_blank">See PDF</a>
</div>
</div>
</div>
And then I use computed to get current href value as:
props: {
tabs: {
type: Array as PropType<Array<any>>,
required: true,
},
},
computed: {
pdfSrc(): string {
return `/img/modal/pdf/${encodeURIComponent(this.tabs[0].pdf)}.pdf`
},
}
As you can see I always use tabs[0]
so pdf value is always value name1
and I want to get depending of the selected tab
The tab method:
setup(props) {
const changeTab = (selectedTab: { id: number }) => {
props.tabs?.map((t) => {
t.id === selectedTab.id ? (t.current = true) : (t.current = false)
})
}
return {
changeTab,
}
},
How can I change static index 0 to dynamic one depending on the current tab?
CodePudding user response:
I would suggest creating a new variable for tracking the selected tab.
const selectedTabId = ref(0);
Similar to tabs
, this could be passed down in array and the value updated in changeTab
function.
props: {
tabs: {
type: Array as PropType<Array<any>>,
required: true,
},
selectedTabId: {
type: Number
}
},
setup(props) {
const changeTab = (selectedTab: { id: number }) => {
selectedTabId = selectedTab.id
props.tabs?.map((t) => {
t.id === selectedTab.id ? (t.current = true) : (t.current = false)
})
}
return {
changeTab,
}
},
Finally in the computed use selectedTabId
computed: {
pdfSrc(): string {
return `/img/modal/pdf/${encodeURIComponent(this.tabs[this.selectedTabId].pdf)}.pdf`
},
}