简体   繁体   English

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

[英]How to use VueJS 2 global components inside single file components?

I am trying to use a globally registered component (with Vue.component ) inside a single file component but I am always getting 我试图在单个文件组件中使用全局注册的组件(使用Vue.component )但我总是得到

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

For example: 例如:

main.js: main.js:

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

home.vue: 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>

You don't need the module.exports. 您不需要module.exports。 You can register the component globally by having this within the mycomponent.vue file. 您可以在mycomponent.vue文件中全局注册该组件。

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

Then add to main.js 然后添加到main.js

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

or I typically register them in a 'globals' file them import that into the main. 或者我通常在'全局'文件中注册它们,然后将它们导入到主文件中。

That should then allow you to use my-component anywhere in the app. 这应该允许您在应用程序的任何位置使用my-component。

Component.vue Component.vue

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

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

Use this component in home.vue: 在home.vue中使用此组件:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM