gpt4 book ai didi

vue.js - Vue 3 : component `:is` in for loop fails

转载 作者:行者123 更新时间:2023-12-01 23:05:03 26 4
gpt4 key购买 nike

我正在尝试遍历 strings 描述的组件列表(我从另一个获取组件的名称,例如 const componentTreeName = ["CompA", "CompA"]

我的代码很简单:

<script setup>
import CompA from './CompA.vue'
import { ref } from 'vue'

// I do NOT want to use [CompA, CompA] because my inputs are strings
const componentTreeName = ["CompA", "CompA"]
</script>

<template>
<h1>Demo</h1>
<template v-for="compName in componentTreeName">
<component :is="compName"></component>
</template>
</template>

Demo here

编辑

我试过了 this没有太大的成功。

最佳答案

使用resolveComponent()在组件名称上按名称查找全局组件:

<script setup>
import { resolveComponent, markRaw } from 'vue'
const myGlobalComp = markRaw(resolveComponent('my-global-component'))
</script>

<template>
<component :is="myGlobalComp" />
<template>

demo 1

如果您混合使用本地和全局注册的组件,则可以使用查找本地组件,然后回退到 resolveComponent() 获取全局组件:

<script setup>
import LocalComponentA from '@/components/LocalComponentA.vue'
import LocalComponentB from '@/components/LocalComponentB.vue'
import { resolveComponent, markRaw } from 'vue'

const localComponents = {
LocalComponentA,
LocalComponentB,
}

const lookupComponent = name => {
const c = localComponents[name] ?? resolveComponent(name)
return markRaw(c)
}

const componentList = [
'GlobalComponentA',
'GlobalComponentB',
'LocalComponentA',
'LocalComponentB',
].map(lookupComponent)
</script>

<template>
<component :is="c" v-for="c in componentList" />
</template>

demo 2

注意: markRaw用于组件定义,因为它不需要 react 性。

关于vue.js - Vue 3 : component `:is` in for loop fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71083006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com