[Vuejs]-Vue 3 – How do I force render a dynamic component?

1👍

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>

0👍

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

Leave a comment