Vue 组件的嵌套
组件的嵌套:子组件以标签的形式要在父组件的模板中使用
template 模板内直接子元素有且仅有一个 (所以套个div)
<div id="root">
</div>
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义student组件
const student = Vue.extend({
name:'student',
template:`
<div>
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
data(){
return {
name:'尚硅谷',
age:18
}
}
})
//定义school组件
const school = Vue.extend({
name:'school',
template:`
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<student></student>
</div>
`,
data(){
return {
name:'尚硅谷',
address:'北京'
}
},
//注册组件(局部)
components:{
student
}
})
//定义hello组件
const hello = Vue.extend({
template:`<h1>{{msg}}</h1>`,
data(){
return {
msg:'欢迎来到尚硅谷学习!'
}
}
})
//定义app组件
const app = Vue.extend({
template:`
<div>
<hello></hello>
<school></school>
</div>
`,
components:{
school,
hello
}
})
//创建vm
new Vue({
template:'<app></app>',
el:'#root',
//注册组件(局部)
components:{app}
})
关于VueComponent:
-
school
组件本质是一个名为VueComponent
的构造函数,且不是程序员定义的,是Vue.extend
生成的。 -
我们只需要写
<school/>
或<school></school>
,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。 -
特别注意:每次调用Vue.extend,返回的都是一个全新的
VueComponent
!!!! -
关于this指向:
(1). 组件配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent
实例对象】。
(2).new Vue(options)
配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue
实例对象】。 -
VueComponent
的实例对象,以后简称vc
(也可称之为:组件实例对象)。
Vue
的实例对象,以后简称vm
。