Unknown custom element: <button-counter> - did you register the component correctly?
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
·
今天学习 Vue 组件,写了一个小案例,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="components-demo">
<button-counter></button-counter>
</div>
<script>
// 创建 Vue 实例
let vm = new Vue({
el: '#components-demo',
data: {}
})
// 全局注册
Vue.component('button-counter', {
data() {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
</script>
</body>
</html>
在浏览器打开后没有出现预期效果,打开控制台后报错如下:
vue.js:634 [Vue warn]: Unknown custom element: <button-counter> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
错误原因:组件全局注册需要在 Vue 根实例创建前进行,前面的代码我把两者的顺序写反了。
解决方法:先注册组件,然后再创建 Vue 根实例。
代码修改如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="components-demo">
<button-counter></button-counter>
</div>
<script>
// 全局注册
Vue.component('button-counter', {
data() {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
// 创建 Vue 根实例
let vm = new Vue({
el: '#components-demo',
data: {}
})
</script>
</body>
</html>
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:4 个月前 )
c345bb45
1 年前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)