首页 > 解决方案 > 如何在 Vue 中使用模块系统导入动态 v-bind:is 组件

问题描述

问题:我正在尝试以编程方式注册要在我的 Vue/Nuxt 站点的插槽中使用的组件。组件名称包含在父index.vue文件的数据中,在这种情况下,组件名为Projects。我将它包含在v-for模板中,因为'modules'迭代数据数组中的各种对象。我曾假设从动态组件文档示例中这是可能的/容易的,但是我没有设法让它在我的情况下工作。

我期望发生的事情:我期望组件被正确注册并“插入”到Module组件中。

实际发生的情况:虽然我可以在渲染视图上看到组件“存在”,但它不在正确的位置(即插入Module组件中)。我也收到一条vue/no-unused-components错误消息:The "Projects" component has been registered but not used.

我已经阅读了有关模块化系统中组件注册的文档,但这些似乎是针对比我想要实现的更复杂的情况。任何建议都会非常有帮助,因为我完全被卡住了!

index.vue

<template>
  <div>
    <template v-for="module in modules">
      <Module
        :title="module.title"
        :to="module.link"
      />
      <component v-bind:is="module.slot" />
      </Module>
    </template>
  </div>
</template>

<script>
import Module from '~/components/module/Module.vue'
import Projects from '~/components/module/slots/Projects.vue'
export default {
  components: {
    Module,
    Projects
  },
  data () {
    return {
      modules: [
        {
          title: 'Work',
          slot: 'Projects'
        },
        {
          ...
        }
      ]
    }
  }
}
</script>

编辑:作为旁注,我在注册组件时遇到同样的错误,import如下所示:

components: {
  Module,
  'Projects': () => import('@/components/module/slots/Projects')
}

Module.vue

<template>
  <div>
    <h2>
      {{ title }}
    </h2>
    <slot />
  </div>
</template>
<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    }
  }
}
</script>

Projects.vue

<template>
  <div>
    <h3>Projects</h3>
  </div>
</template>
<script>
export default {
  name: 'Projects'
}
</script>

标签: javascriptvue.jswebpackvuejs2progressive-web-apps

解决方案


您在Module组件中使用自闭标签。

这可以防止您的Projects组件在插槽内呈现。

只需更换:

<Module
   :title="module.title"
    :to="module.link"
/>

和:

<Module
   :title="module.title"
    :to="module.link"
>

它应该可以工作。


推荐阅读