在下面的代码示例中(在VueJS官网引用):
<script setup>
import Home from './Home.vue'
import Posts from './Posts.vue'
import Archive from './Archive.vue'
import { ref, watch } from 'vue'
let currentTab = ref('Home')
const tabs = {
Home,
Posts,
Archive
}
watch(currentTab, (currentTab) => console.log(tabs[currentTab], currentTab))
</script>
<template>
<div class="demo">
<button
v-for="(_, tab) in tabs"
:key="tab"
:class="['tab-button', { active: currentTab === tab }]"
@click="currentTab = tab"
>
{{ tab }}
</button>
<component :is="tabs[currentTab]" class="tab"></component>
</div>
</template>
<style>
.demo {
font-family: sans-serif;
border: 1px solid #eee;
border-radius: 2px;
padding: 20px 30px;
margin-top: 1em;
margin-bottom: 40px;
user-select: none;
overflow-x: auto;
}
.tab-button {
padding: 6px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ccc;
cursor: pointer;
background: #f0f0f0;
margin-bottom: -1px;
margin-right: -1px;
}
.tab-button:hover {
background: #e0e0e0;
}
.tab-button.active {
background: #e0e0e0;
}
.tab {
border: 1px solid #ccc;
padding: 10px;
}
</style>
摘自
Code Example Reference on VueJS Official Page个
...当我将变量‘CurrentTab’传递给:is属性时(而不是选项卡[CurrentTab],如下所示:
<component :is="currentTab" class="tab"></component>
个
...奇怪的是,组件停止显示,尽管变量‘CurrentTab’的值应该解析为我们单击的组件名称的字符串值(如,‘Home’,或‘Posts’,或‘Archive’,因为您可以看到我通过"watch()"使用sole.log显示的变量的值).
因此,只有当我将"tabs[CurentTab]"传递给:is属性时,或者当我传递组件的字符串名称(Home、or Posts或Archive)时,代码才起作用,如下所示:
<component :is="Archive" class="tab"></component>
//仅显示归档文件
或
<component :is="tabs[currentTab]" class="tab"></component>
//显示单击的组件w.r.t选项卡.
如果变量‘CurrentTab’应解析为其值以提供:
<component :is="Archive" class="tab"></component>
//仅显示归档文件
...那么为什么结果视图中会有奇怪的行为呢?