如何在VueJS 2的单文件组件中使用全局组件?

25

我正在尝试在单文件组件中使用全局注册的组件(使用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
@Elfayer 所有内容都包含在由Vueify创建的捆绑包中,主页组件在main.js文件中是必需的。 - J. Molinero
2个回答

51

你不需要使用 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.export_和_require_。 - J. Molinero
= should be removed in export default = {} - Alexander
2
非常感谢。我花了两天时间阅读文档和 SO,试图理解如何全局声明单页组件,而语法只是Vue.component('my-component', MyComponent); :) - Overdrivr
非常感谢你!你能告诉我 Vue.component('card', require('./components/card.vue'));import Card from './components/card.vue'; Vue.component('card', Card); 两者之间的区别吗? - Pardeep Jain
1
@PardeepJain 这两个语句的结果是相同的。前者使用了UMD require函数,这是一种包含模块化Javascript依赖项的临时解决方案。后者使用了现代的ES6 import标准语法(虽然它仍处于早期阶段,因此经常不被支持,所以任何使用import语句的脚本现在可能需要转换为普通的require风格JS)。 - Rafe Goldberg
@J.Molinero,从原帖来看,第一个例子即在本地主机上不注册就可以运行。那么采用这种方式编码有什么问题吗? - Istiaque Ahmed

3

Component.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>

6
我不想在本地注册“my-component”,我希望能够在整个应用程序中使用它,因此我想使用“Vue.component”在全局范围内注册它。 - J. Molinero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接