我正在嘗試使用 Vue 3.2 中的動態組件開發選項卡,但組件未顯示。如果我更改<component :is=currentTab ></component>為<A/>,它會出現,所以我認為<component></component>無法正常作業,但我不知道為什么。如果您能給我一些建議,我將不勝感激。謝謝你。
<template>
<div class="flex-column">
<div class="header" >
<div id="dynamic-component-demo" class="demo">
<button
v-for="tab in tabs"
v-bind:key="tab"
v-bind:class="['tab-button', { active: currentTab === tab }]"
v-on:click="currentTab = tab"
>
{{ tab }}
</button>
<component :is=currentTab ></component>
</div>
</div>
</div>
<template>
<script setup lang="ts">
import Shop from './A/A.vue';
import Knowledge from './B/B.vue';
import Community from './C/C.vue';
import router from '../../router';
const currentTab= ref('A');
const tabs = ['A', 'B', 'C']
</script>
uj5u.com熱心網友回復:
當然,它不起作用。您的組件未按名稱注冊。Vue 怎么知道它"A"應該是Shop組件?
您有 2 個選項:
全域注冊組件(app.component())或本地(不可能
script setup- normalscript必須與 一起使用script setup)。現在你可以將他們的名字作為Stringintois并且 Vue 會知道該怎么做或者傳遞一個組件物件
:is而不是字串
<template>
<div id="dynamic-component-demo" class="demo">
<button
v-for="(tab, i) in tabs"
v-bind:key="tab.name"
v-bind:class="['tab-button', { active: currentTab.name === tab.name }]"
v-on:click="currentTab = tabs[i]"
>
{{ tab.name }}
</button>
<component :is="currentTab.comp"></component>
</div>
</template>
<script setup lang="ts">
import { shallowRef } from 'vue'
import Shop from './A.vue';
import Knowledge from './B.vue';
const tabs = [
{ name: 'A', comp: Shop },
{ name: 'B', comp: Knowledge }
]
// using shallowRef to stop Vue from turning component definitions to reactive objects
// use normal ref to see a warning
const currentTab = shallowRef(tabs[0]);
</script>
演示
如果我更改<component :is=currentTab ></component>為<A/>,它會顯示
好吧,我真的對此表示懷疑-當然,除非您在其他地方全域注冊了組件(在問題中未顯示的代碼中)。如果您嘗試添加<A/>到<template>鏈接的演示中,它不起作用...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/451593.html
