今天完成的是一个组件嵌套功能,实现的是如下效果,其中school1 与school2是同级关系
我是这么想的:先用
app
去接管vm
中的所有组件,app
中有school1
组件和school2
组件,然后在school1
中嵌套student
,student
组件中嵌套hello
在解决组件
school1
与schoo2
同级关系时,控制台报了如下错误,奇奇怪怪的错误让我school1
与school2
不能同时出现
在经过理解转化之后,修改代码前后对比如下【后者为正确代码】
话不多说,直接上代码理解
<!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="root">
<app></app>
</div>
<script>
// 定义hello组件
const hello = Vue.extend({
template:`
<h2>{{message}}</h2>
`,
data(){
return{
message:'欢迎来到Vue开发学习'
}
}
})
// 定义student子组件
const student = Vue.extend({
name:'student',
template:`
<div>
<h2>学生姓名名称:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
<hello></hello>
</div>
`,
data(){
return{
name:'张小北',
age:18
}
},
// 注册组件(局部)
components:{
hello
}
})
// 定义school父组件
const school1 = Vue.extend({
name:'school1',
template:`
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<student></student>
</div>
`,
data(){
return{
name:'长治学院',
address:'长治'
}
},
// 注册组件(局部)
components:{
student
}
})
const school2 = Vue.extend({
template:`
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
`,
data(){
return{
name:'北京大学',
address:'北京'
}
},
/* // 注册组件(局部)
components:{
}*/
})
// 定义app组件
const app = Vue.extend({
template:`
<div>
<school1></school1>
<school2></school2>
</div>
`,
components:{
school1,
school2
}
})
// 创建vm
new Vue({
el:'#root',
// 注册组件(局部)
components:{
app
}
})
</script>
</body>
</html>