【问题标题】:With Nuxt's auto import of components, how to use the <component> element?使用 Nuxt 的自动导入组件,如何使用 <component> 元素?
【发布时间】:2021-06-15 04:16:48
【问题描述】:

Nuxt.js v2.13 起自动导入组件。

但是我们如何使用&lt;component :is="MyComponent" /&gt;

这样写会报错:

MyComponent 未定义

在这种情况下,我们是否应该以常规方式导入组件(例如import MyComponent from '@/components/MyComponent'),如果这样,组件不会被导入两次吗?

编辑:

脚本:

export default {
  data () {
    return {
      componentNames: {
        index: 'ButtonSection',
        large_banner: 'LargeBanner',
        small_banner: 'SmallBanner'
      }
    }
  },
  computed: {
    ...mapState({
      sections: state => state.sections.section_list ?? null
    })
  }
}
</script>

模板:

<template v-if="sections">
  <component
    :is="componentNames[sections[i].section_type]"
    v-for="(section, i) in sections"
    :key="i"
  />
</template>

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    当您使用绑定符号: 时,模板会看到组件实例中已定义的属性,如果您不提供该符号作为字符串的标记,如果您要添加此配置:

    export default {
      components: true
    }
    

    组件会自动解析,您可以像这样使用它:

    <component is="ComponentName" />
    

    或使用原始字符串绑定:

    <component :is="'ComponentName'" />
    

    或使用属性绑定:

    <component :is="MyComponent" />
    
    ...
    
    data(){
       return{
       MyComponent:'ComponentName'
     }
    }
    

    【讨论】:

    • 您确定我们可以在不使用: 的情况下使用&lt;component is="" /&gt; 吗?当我这样做时,我收到一个错误“预期 '' 元素具有 'v-bind:is' 属性”。同样在我的示例中,“MyComponent”是我尝试使用的组件的实际名称。
    • : 要求在脚本属性中定义MyComponent,或者您可以使用:is="'MyComponent'"
    • 现在可以工作了,非常感谢:) 一件事:在我的脚本中,MyComponent 实际上存储在一个变量中。如果我这样做&lt;component :is="'variable'"&gt; 显然它不起作用,因为variable 被视为字符串并且JS 不明白我想要variable 的内容。你明白我的意思吗?在这种情况下,我怎样才能使它工作?具体来说,在我的脚本中,它不仅仅是variable,而是:componentNames[sections[i].section_type]
    • 没有 pb,我编辑了问题并添加了整个代码
    • 对不起兄弟,你是对的,它现在可以工作了。不知道发生了什么。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 2021-02-04
    • 1970-01-01
    • 2017-10-29
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多