Javascript 如何在单文件组件中使用VueJS 2全局组件?
我试图在单个文件组件中使用全局注册的组件(带有Vue.component),但我总是得到Javascript 如何在单文件组件中使用VueJS 2全局组件?,javascript,vue.js,vue-component,Javascript,Vue.js,Vue Component,我试图在单个文件组件中使用全局注册的组件(带有Vue.component),但我总是得到 vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the component correctly? vue.common.js:2611[vue warn]:未知自定义元素:-您是否正确注册了组件? 例如: main.js: ... Vue.component('my
vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the component correctly?
vue.common.js:2611[vue warn]:未知自定义元素:-您是否正确注册了组件?
例如:
main.js:
...
Vue.component('my-component', {
name: 'my-component',
template: '<div>A custom component!</div>'
})
...
。。。
Vue.component(“我的组件”{
名称:“我的组件”,
模板:“自定义组件!”
})
...
home.vue:
<template>
<div>
<my-component></my-component>
</div>
</template>
<script>
module.exports = {
name: 'home'
}
</script>
<template>
<div>
<my-component></my-component>
</div>
</template>
<script>
import component from './component.vue'
export default {
components: { my-component: component }
}
</script>
module.exports={
姓名:“家”
}
如果我在本地注册,它可以正常工作:
<template>
<div>
<my-component></my-component>
</div>
</template>
<script>
module.exports = {
name: 'home',
components: {
'my-component': require('./my-component.vue')
}
}
</script>
module.exports={
姓名:'家',
组成部分:{
“我的组件”:需要(“./my component.vue”)
}
}
Component.vue
<template><div>A custom component!</div></template>
<script>export default { code here... }</script>
自定义组件!
导出默认值{code here…}
在home.vue中使用此组件:
<template>
<div>
<my-component></my-component>
</div>
</template>
<script>
import component from './component.vue'
export default {
components: { my-component: component }
}
</script>
从“./component.vue”导入组件
导出默认值{
组件:{my component:component}
}
您不需要module.exports。您可以在mycomponent.vue文件中全局注册组件
<template>
<div>A custom component!</div>
</template>
<script>
export default {}
</script>
或者我通常将它们注册到一个“globals”文件中,然后将其导入到主文件中
这样,您就可以在应用程序中的任何位置使用我的组件。您需要在某个位置使用该组件,否则它将无法下载。@ellayer所有内容都在Vueify创建的包中,主组件在main.js文件中是必需的。我不想在本地注册我的组件,我不想在整个应用程序中都使用它,因此我想使用Vue.component全局注册它。我想使用browserify/vueify和ES5。因此,我必须使用module.export和require。
=
应该在export default={}
中删除,非常感谢。我花了两天时间阅读文档,试图理解如何全局声明一个单页组件,而语法只是Vue.component('my-component',MyComponent)代码>:)非常感谢你,伙计!你能告诉我两者的区别吗Vue.component('card',require('./components/card.Vue')代码>和从“./components/Card.vue”导入卡;Vue.组件(“卡”,卡)代码>?@PardeepJain这两个语句的计算结果相同。前者使用UMDrequire
函数,这是包含模块化Javascript依赖项的临时解决方案。后者使用现代ES6import
标准语法(虽然它仍处于早期阶段,因此经常不受支持,因此任何使用import
语句的脚本现在都可能需要传输到vanillarequire
风格的JS。)