skip to Main Content

How do I force render a dynamic component?

In this case only the last tab’s component mounts. I want them all to mount once.

const addTab = (symbol: string) => {
  const id = nextTabId++;
  tabs.value.push({
    id,
    symbol,
    component: markRaw(ChartComponent),
  });
  activeTabId.value = id;
};

onMounted(() => {
  addTab("USD");
  addTab("EUR");
});

  <KeepAlive>
    <component
      :key="activeTab?.id"
      :is="activeTab?.component"
    />
  </KeepAlive>

2

Answers


  1. Since it’s a tab, only one content component is needed at once. I’ve tried a simple solution. Hope this helps.

    <script setup lang="ts">
    import { onMounted, ref, reactive } from 'vue';
    import ChartComponent from './ChartComponent.vue';
    interface Tab {id: number, symbol: string}
    const tabs: Tab[] = reactive([]);
    let nextTabId = 0
    const activeTabId = ref(0)
    
    const addTab = (symbol: string) => {
      const id = nextTabId++;
      tabs.push({
        id,
        symbol,
      });
    };
    
    onMounted(() => {
      addTab("USD");
      addTab("EUR");
    });
    </script>
    <template>
    <div class="tabs" v-if="tabs.length">
      <button v-for="tab in tabs" :key="tab.id"
        @click="activeTabId = tab.id"
      >
        {{tab.id}} - {{ tab.symbol }}
      </button>
    </div>
    <div class="tab-content">
      <component :is="ChartComponent" :symbol="tabs[activeTabId].symbol"/>
    </div>
    </template>
    

    Note:
    If different components for different tab items are required, then they can be put into the tabs array with a new component property, which should trigger no issue. Dynamic props can be fed using v-bind attribute in the component.

    Demo

    Login or Signup to reply.
  2. Not using KeepAlive and use v-show

    <div v-for="tab in tabs" :key="tab.id">
      <component :is="tab.component" v-show="activeTabId === tab.id"/>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search