问题描述
限时送ChatGPT账号..我正在使用实验性的 脚本设置 以创建学习环境.我有一个自制的导航栏,打开单个组件.
I am using the experimental script setup to create a learn enviroment. I got a selfmade navigation bar with open a single component.
我在使用
I am having trouble using the <component :is="" />
method. This method is described in the docs under component basics -> dynamic-components
在 Vue 3 Composition API 中,它按预期工作:
In the Vue 3 Composition API, it works as expected:
<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>
我使用 脚本设置
的方法失败了:
My approach with the script setup
fails:
<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>
你知道如何用脚本设置方法解决这个问题吗?
do you got any idea how to solve this with the script setup method?
推荐答案
好像用,
tab
需要引用组件定义本身而不是组件名称.
It seems with <script setup>
, tab
needs to reference the component definition itself instead of the component name.
要引用不需要反应性的组件定义,请使用 设置
:tab.value
之前的markRaw()
To reference the component definition, which does not need reactivity, use markRaw()
before setting tab.value
:
<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>
演示1
如果您需要将组件名称传递给 changeTab()
,您可以使用查找:
If you need to pass the component name to changeTab()
, you could use a lookup:
<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>
演示2
使用 Vue 3.0.9
设置和 Vue CLI 测试 5.0.0-alpha.8
Tested with Vue 3.0.9
setup with Vue CLI 5.0.0-alpha.8
这篇关于如何使用<component :is="">在 vue 3 脚本设置中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论