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

2024-01-03

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

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>'
})
...

主页.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>

您不需要 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。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐