如何在单个文件组件中使用VueJS 2全局组件? [英] How to use VueJS 2 global components inside single file components?

查看:69
本文介绍了如何在单个文件组件中使用VueJS 2全局组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use a globally registered component (with Vue.component) inside a single file component but I am always getting

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>

如果我在本地注册,它就可以了:

If I register it locally, it works OK:

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


推荐答案

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

You don't need the module.exports. You can register the component globally by having this within the mycomponent.vue file.

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

然后添加到main.js

Then add to main.js

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

或者我通常在'globals'文件中注册它们,然后将它们导入到主文件中。

or I typically register them in a 'globals' file them import that into the main.

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

That should then allow you to use my-component anywhere in the app.

这篇关于如何在单个文件组件中使用VueJS 2全局组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆