首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue 3:组件‘:in’in for循环失败

Vue 3:组件‘:in’in for循环失败
EN

Stack Overflow用户
提问于 2022-02-11 15:57:08
回答 2查看 792关注 0票数 2

我试图循环一个由字符串描述的组件列表(我从另一个组件获得该组件的名称,比如const componentTreeName = ["CompA", "CompA"] )。

我的代码很简单,如下:

代码语言:javascript
复制
<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>

这里的演示

编辑

我尝试了,但没有取得多大的成功。

EN

回答 2

Stack Overflow用户

发布于 2022-02-12 00:50:29

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

代码语言:javascript
复制
<script setup>
import { resolveComponent, markRaw } from 'vue'
const myGlobalComp = markRaw(resolveComponent('my-global-component'))
</script>

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

演示1

如果您混合了本地和全球注册的组件,则可以使用查找本地组件的方法,然后返回到全局的resolveComponent()

代码语言:javascript
复制
<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>

演示2

注释: https://vuejs.org/api/reactivity-advanced.html#markraw用于组件定义,因为它不需要任何反应性。

票数 4
EN

Stack Overflow用户

发布于 2022-02-11 17:33:29

当使用script setup时,您需要引用组件而不是名称或键。

为了使其工作,我将使用一个对象,其中可以使用字符串作为键,从这样的对象中锁定组件:

代码语言:javascript
复制
<script setup>
    import CompA from './CompA.vue'
    import { ref } from 'vue'
    const components = {CompA};

    // 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="components[compName]"></component>
  </template>
</template>

要使用全局组件,可以通过从应用程序上下文中提取组件来分配组件。但是这需要app上下文是可用的,并且密钥是已知的。

示例:

代码语言:javascript
复制
import { app } from '../MyApp.js'
const components = {
  CompA: app.component('CompA')
}

我还没有测试过这个,但这可能值得一试,与getCurrentInstance检查一下

代码语言:javascript
复制
import { ref,getCurrentInstance } from 'vue'
const components = getCurrentInstance().appContext.components;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71083006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档