一、组件嵌套
1.声明子组件
//子组件
let zi= {
template:'#zi'
}
2.声明父组件
//父组件
let fu= {
template:'#fu',
//父组件嵌套子组件的时候,需要用components
components: {
zi
}
}
注意:谁被嵌套谁写到前面,比如父组件嵌套子组件,那么子组件要写到父组件前面去
3.声明new Vue
new Vue({
el:'#app',
//组件嵌套,父嵌套子,那么在页面渲染的时候,只需要父的组件就可以了
components:{
fu
}
})
4.html
<div id="app">
<fu></fu>
</div>
<!-- 这是父组件-->
<template id="fu">
<div>
<h1>我是父组件</h1>
<zi></zi>
</div>
</template>
<!-- 这是子组件-->
<template id="zi">
<h1>我的子组件</h1>
</template>
二、组件通信之父组件传子组件
父组件传子组件的关键点在于props和v-bind实现
1.声明父组件
//父组件
let fu = {
template:'#fu',
components: {
zi
},
//父传子的时候,需要在父组件创建data函数,传值
data:function () {
return {
text:'我是父组件的数据'
}
}
}
2.声明子组件
//子组件
let zi = {
template:'#zi',
//用props来接收父组件传递过来的数据
props:['text']
}
3.声明vue实例
new Vue({
el:'#app',
components:{
fu
}
})
4.html
<div id="app">
<fu></fu>
</div>
<template id="fu">
<div>
<h1>我是一</h1>
<!-- 用v-bind来渲染子组件的数据-->
<two v-bind:text="text"></two>
</div>
</template>
<template id="zi">
<!---这个是props自定义的属性->
<h1>{{text}}</h1>
</template>
三、组件通信之子组件传父组件
利用$emit和v-on实现
1.声明子组件
// 子组件
let ZiComponent = {
template:"#zi",
methods:{
setData(){
// 子传父
// 参数一:自定义事件
// 参数二:要传递的数据
// 执行demo事件并传递参数【执行demo事件绑定的函数并传递参数】
// 执行子组件上的demo事件绑定的函数并传递参数
// demo事件是子组件自定义的事件
// 绑定的函数是父组件中的函数
this.$emit("demo",123);
// 子组件其实是把数据当成参数传递给父组件中的函数
// 子组件执行我’自己的自定义事件
// 自定义事件绑定到父组件中的函数
}
}
}
2.声明父组件
// 父组件
let FuComponent = {
template:"#fu",
components:{ZiComponent},
data:function () {
return {
value:"这是父组件"
}
},
methods:{
handleFu(params){
//params就是从子组件,$emit("demo",123)
//通过demo自定义事件,传递123这个数据
//让params来接收
this.value = params
}
}
}
3.声明vue实例
new Vue({
el:"#app",
components: {FuComponent}
});
4.html
<div id="app">
<fu-component></fu-component>
</div>
<template id="fu">
<div>
<h1 style="color:red;">{{value}}</h1>
<!-- 自定义事件 = 父组件函数 -->
<zi-component @demo="handleFu"></zi-component>
</div>
</template>
<template id="zi">
<div>
<h1>子组件</h1>
<button @click="setData">给父组件传参</button>
</div>
</template>
四、组件通信扩展
属性 | 描述 |
$children | 获取所有的子组件 |
$refs | 获取标签对象 |
$el | 获取标签名 |
$data | 获取组件的data属性 |
$root | 获取根组件 |
$set | 设置数组 |
$parent | 获取父组件 |