Home > database >  Vue3 how to implement dynamic components with Composition API?
Vue3 how to implement dynamic components with Composition API?

Time:09-11

I want to use dynamic component functionality with Composition API in Vue3. I have no problem with Options API. I followed this instruction: link

There is my code:

<script setup>
import { ref } from "vue";
import General from "../components/ContractGeneral.vue";
import Networks from "../components/ContractDetails.vue";
const tabs = {
  General,
  Networks,
};
let currentTab = ref("Networks");
</script>

<template>
  <main>
    <nav>
      <ul>
        <li v-for="tab in tabs" :key="tab" @click="currentTab = tab">
          <div>
            <p>{{ tab }}</p>
          </div>
        </li>
      </ul>
      <div></div>
    </nav>
    <section>
      <keep-alive>
        <component :is="tabs[currentTab]"></component>
      </keep-alive>
    </section>
  </main>
</template>

and the problem is, that {{tab}} in my case shows a full component object, not just a name like 'General'. It shows something like this: "src/components/ContractGeneral.vue", "__hmrId": "f8a99314" }

How can I fix this error?

CodePudding user response:

You could get the tab key from the v-for loop as follows :

 <li v-for="(tab,key,index) in tabs" :key="tab" @click="currentTab = key">
    <div>
     <p>{{ key }}</p>
    </div>
  </li>

  • Related