在下面的代码示例中(在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

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>//仅显示归档文件

...那么为什么结果视图中会有奇怪的行为呢?

推荐答案

:is="Archive":is="tabs[currentTab]"的情况下,值是一个分量,而在:is="currentTab"的情况下,它是一个字符串.

它应该与tabs之类的组件映射一起使用,或者在使用之前进行解析:

let currentTabComp = computed(() => resolveComponent(currentTab.value))

这是not well-supported by script setup syntax,为了使其工作,组件需要在component components option with regular script中显式注册.

Vue.js相关问答推荐

如果似乎没有明确使用输入事件,那么发出输入事件有什么作用?

如何 for each 动态创建的按钮/文本字段设置唯一变量?

组合 API | Vue 路由参数没有被监视

Vuetify 扩展面板,面板标题左侧带有图标

Vue:将点击事件绑定到动态插入的内容

Nuxt.js 中的开发工具样式编辑问题

Vue3在'vue-router'中找不到导出'createWebHistory,createRouter'

如何在不实例化根实例的情况下使用 vue 组件?

错误:您可能需要额外的加载器来处理这些加载器的结果.

Vue test-utils 如何测试 router.push()

Vue.js:TypeError:无法设置只有 getter 的 # 的属性props

Vue路由安全

Vue 3:模块 '"../../node_modules/vue/dist/vue"' 提示

vue 3 使用 Vuex 和路由的服务器端渲染

如何从 vue 组件调用 App.vue 中的方法

Import Unexpected identifier + SyntaxError: Unexpected string

使用 Firebase Auth for Google 将匿名用户转换为注册用户

带有 Google Auth Signin 的 Vuejs 全局函数

Vuejs 组件等待 facebook sdk 加载

如何订阅store 模块