今天学习 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>