1

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?

1 Answer 1

1

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`
    },
 }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried to declare constant, then assign in function but it is returning an error: Cannot assign to selectedTabId because it is a constant
Ohh, it is beacuse I do not use generics so it is selectedTabId.value = selectedTab.id, excellent answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.