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

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

问题描述

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

vue.common.js:2611[Vue 警告]:未知的自定义元素:<my-component>- 您是否正确注册了组件?

例如:

main.js:

<代码>...Vue.component('我的组件', {名称:'我的组件',template: '<div>一个自定义组件!</div>'})...

home.vue:

<模板>

<我的组件></我的组件></div></模板><脚本>模块.exports = {名称:家"}</脚本>

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

<模板>

<我的组件></我的组件></div></模板><脚本>模块.exports = {名称:'家',组件: {'我的组件':需要('./my-component.vue')}}</脚本>

解决方案

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

<模板><div>自定义组件!</div></模板><脚本>导出默认 {}</脚本>

然后添加到main.js中

从 './component.vue' 导入 MyComponentVue.component('my-component', MyComponent);

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

这应该允许您在应用程序的任何地方使用 my-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?

For example:

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>

解决方案

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>

Then add to 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.

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

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