报错内容: [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the “name” option.
报错分析: 组件化注册未成功。
场景分析:
以局部组件化TodoList为例–报上述错误
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TodoList</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button v-on:click="handleBtnClick">提交</button>
<ul>
<!-- 循环标签 -->
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
// 创建一个局部组件
var TodoItem = {
props: ['content'],
template:"<li>{{content}}</li>",
};
var app = new Vue({
el:'#app',
data:{
list:[],
inputValue:''
},
methods:{
handleBtnClick:function(){
this.list.push(this.inputValue);
this.inputValue = '';
}
}
})
</script>
</body>
</html>
处理后的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TodoList</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js"></script>
</head>
<body>
<!-- 组件化改造内容:list标签组件化 -->
<div id="app">
<input type="text" v-model="inputValue">
<button v-on:click="handleBtnClick">提交</button>
<ul>
<!-- todo-item就是组件名TodoItem,这里不区分大小写 -->
<!-- v-bind绑定值 -->
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
// 创建一个局部组件
var TodoItem = {
props: ['content'], // 接收外部传入的v-bind:content的值
template:"<li>{{content}}</li>", // 创建一个模板
};
var app = new Vue({
el:'#app',
components:{
TodoItem:TodoItem // 将TodoItem注册到Vue实例之中,原来叫TodoItem,现在仍然叫TodoItem。
},
data:{
list:[],
inputValue:''
},
methods:{
handleBtnClick:function(){
this.list.push(this.inputValue);
this.inputValue = '';
}
}
})
</script>
</body>
</html>