How to use VueJS 2 global components inside single file components?(如何在单个文件组件中使用 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 全局组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在单个文件组件中使用 VueJS 2 全局组件?


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01