【问题标题】:Composition API + script setup Dynamic componentComposition API + 脚本设置动态组件
【发布时间】:2022-12-08 07:45:46
【问题描述】:
我想使用脚本设置和组合 API 实现简单的选项卡
<script setup>
import Timeline from './Timeline.vue';
import Profile from './Profile.vue';
import Groups from './Groups.vue';
const currentTab = ref('Timeline')
const tabs = ref(['Timeline', 'Profile', 'Groups'])
</script>
<template>
<div class="tabs">
<div v-for="tab in tabs"
:key="tab"
@click="currentTab = tab" v-text="tab"
<component :is="currentTab"></component>
</div>
</template>
但是这段代码只会产生<timeline></timeline>,而不是时间轴组件的实际内容。
【问题讨论】:
标签:
vuejs3
vue-composition-api
vue-script-setup
【解决方案1】:
如 here 所述,当使用 <script setup> 方法时,您需要将组件的实际对象传递给 :is 而不是字符串。
See this Example here
这也是代码本身:
<script setup>
import Timeline from './Timeline.vue';
import Profile from './Profile.vue';
import Groups from './Groups.vue';
import { ref } from 'vue';
const currentTab = ref(Timeline);
const tabs = [Timeline, Profile, Groups];
function changeTab(tab) {
currentTab.value = tab;
console.log(tab);
}
</script>
<template>
<div class="tabs">
<div v-for="tab in tabs"
:key="tab"
@click="currentTab = tab" v-text="tab.__name">
</div>
</div>
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
</template>