如何在 vue 3 脚本设置中使用 <component :is="">

How to use <component :is=""> in vue 3 script setup

我正在使用实验性 script setup 来创建学习环境。我有一个自制的导航栏,打开单个组件。

我在使用 <component :is="" /> 方法时遇到问题。 component basics -> dynamic-components

下的文档中描述了此方法

在 Vue 3 组合 API 中,它按预期工作:

<template>
  <NavigationBar
    @switchTab="changeTab"
    :activeTab="tab"
  />
  <component :is="tab" />
</template>

<script>
import { ref } from 'vue'
import NavigationBar from './components/NavigationBar.vue'
import TemplateSyntax from './components/TemplateSyntax.vue'
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'

export default {
  components: {
    NavigationBar,
    TemplateSyntax,
    DataPropsAndMethods
  },
  setup () {
    const tab = ref('DataPropsAndMethods')
    function changeTab (newTab) {
      tab.value = newTab
    }

    return {
      changeTab,
      tab
    }
  }
}
</script>

我使用 script setup 的方法失败了:

<template>
  <NavigationBar
    @switchTab="changeTab"
    :activeTab="tab"
  />
  <component :is="tab" />
</template>

<script setup>
import NavigationBar from './components/NavigationBar.vue'
import TemplateSyntax from './components/TemplateSyntax.vue'
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref } from 'vue'

const tab = ref('DataPropsAndMethods')
function changeTab (newTab) {
  tab.value = newTab
}
</script>

你知道如何使用脚本设置方法解决这个问题吗?

似乎 <script setup>tab 需要引用组件定义本身而不是组件名称。

要引用不需要反应性的组件定义,请在设置tab.value之前使用markRaw():

<script setup>
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref, markRaw } from 'vue'

const tab = ref(null)

changeTab(DataPropsAndMethods)

// newTab: component definition (not a string)
function changeTab (newTab) {
  tab.value = markRaw(newTab)
}
</script>

demo 1

如果您需要将组件名称传递给 changeTab(),您可以使用查找:

<script setup>
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref, markRaw } from 'vue'

const tab = ref(null)

changeTab('DataPropsAndMethods')

// newTab: component name (string)
function changeTab (newTab) {
  const lookup = {
    DataPropsAndMethods,
    /* ...other component definitions */
  }
  tab.value = markRaw(lookup[newTab])
}
</script>

demo 2

使用 Vue 测试 3.0.9 使用 Vue CLI 安装 5.0.0-alpha.8