【问题标题】:How to use VueJS 2 global components inside single file components?如何在单个文件组件中使用 VueJS 2 全局组件?
【发布时间】:2017-03-12 22:17:57
【问题描述】:

我正在尝试在单个文件组件中使用全局注册的组件(带有 Vue.component),但我总是得到

vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the component correctly?

例如:

main.js:

...
Vue.component('my-component', {
    name: 'my-component',
    template: '<div>A custom component!</div>'
})
...

home.vue:

<template>
    <div>
        <my-component></my-component>
    </div>
</template>
<script>
    module.exports = {
        name: 'home'
    }
</script>

如果我在本地注册它,它可以正常工作:

<template>
    <div>
        <my-component></my-component>
    </div>
</template>
<script>
module.exports = {
    name: 'home',
    components: {
        'my-component': require('./my-component.vue')
    }
}
</script>

【问题讨论】:

  • 您需要在某处要求该组件,否则将无法下载。
  • @Elfayer 一切都在 Vueify 创建的包中,主组件在 main.js 文件中是必需的。

标签: javascript vue.js vue-component


【解决方案1】:

您不需要 module.exports。你可以通过在 mycomponent.vue 文件中注册组件来全局注册。

<template>
    <div>A custom component!</div>
</template>
<script>
    export default {}
</script>

然后添加到main.js中

import MyComponent from './component.vue'
Vue.component('my-component', MyComponent);

或者我通常将它们注册到“全局”文件中,然后将其导入主文件。

这应该允许您在应用程序的任何地方使用 my-component。

【讨论】:

  • 我使用 browserify / vueify 和 ES5。因此,我必须使用 module.exportrequire.
  • = 应在 export default = {} 中删除
  • 非常感谢。我花了两天时间阅读文档和 SO,试图了解如何全局声明单页组件,而语法只是 Vue.component('my-component', MyComponent); :)
  • 非常感谢你!你能告诉我Vue.component('card', require('./components/card.vue'));import Card from './components/card.vue'; Vue.component('card', Card);有什么区别吗?
  • @PardeepJain 这两个语句的计算结果相同。前者使用 UMD require 函数,这是包含模块化 Javascript 依赖项的临时解决方案。后者使用现代 ES6 import 标准语法(尽管它仍处于早期阶段,因此通常不受支持,因此任何使用 import 语句的脚本现在可能需要转换为 vanilla require 样式的 JS。 )
【解决方案2】:

组件.vue

<template><div>A custom component!</div></template>

<script>export default { code here... }</script>

在 home.vue 中使用这个组件:

<template>
    <div>
        <my-component></my-component>
    </div>
</template>

 <script>
    import component from './component.vue'
    export default {
     components: { my-component: component }
    }
</script>

【讨论】:

  • 我不想在本地注册 my-component,我不能在整个应用程序中使用它,因此我想注册它全局使用 Vue.component
猜你喜欢
  • 1970-01-01
  • 2022-07-04
  • 2019-05-09
  • 2020-03-16
  • 2020-07-10
  • 2021-05-25
  • 1970-01-01
  • 2020-10-04
  • 2023-03-11
相关资源
最近更新 更多