vue组件的关系分为3种:
1.父子组件
2.兄弟组件
3.嵌套多层的组件
A父子组件
父组件:用:age的方式把age传给子组件,用v-on的方式租接收子组件传来的参数
<template>
<div class="father">
<Child :age='age' v-on:addAge='addAge'/>
</div>
</template>
<script>
import Child from './child.vue'
export default {
name:'father',
data(){
return{
age:'18'
}
},
methods:{
addAge(v){
console.log(v)
}
},
components:{Child}
}
</script>
子组件:用props去接收父组件传下来的参数,用this.$emit(key,value)的方式将子组件的信息传给父组件
<template>
<div class="child">
年龄是{{age}}
<p @click="addAge">增加年龄</p>
</div>
</template>
<script>
export default {
name:'child',
props:['age'],
methods:{
addAge(){
this.$emit('addAge','19')
}
}
}
</script>
B兄弟组件
兄弟组件的通信需要借助一个中转站bus;
bus.js中主要是实例化vue
import Vue from 'vue'
export default new Vue;
父组件:
<template>
<div class="father">
<Brother1/>
<Brother2/>
</div>
</template>
<script>
import Brother1 from './brother1.vue'
import Brother2 from './brother2.vue'
export default {
name:'father',
components:{Brother1,Brother2}
}
</script>
兄弟1组件:手动点击事件,将值传给兄弟2组件,通过引入bus,使用bus.$emit方法
<template>
<div class="child">
<p @click="handleClick">点击</p>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data(){
return{
age:'18'
}
},
name:'brother1',
methods:{
handleClick(){
Bus.$emit('age',this.age)
}
}
}
</script>
兄弟2组件:通过引入bus,使用bus,$on去接收
<template>
<div class="child">
年龄是{{age}}
</div>
</template>
<script>
import Bus from './bus.js'
export default {
name:'brother2',
data(){
return{
age:null
}
},
mounted(){
this.$nextTick(function(){
Bus.$on('age',(v)=>{
this.age=v
})
})
}
}
</script>
C嵌套多层的组件
在vue2.4以前,有2种方法可处理:
①通过父子组件层层往下级传
②使用vuex,统一管理数据
这里介绍vue2.4的一个方法,
a
t
t
r
s
及
attrs及
attrs及listeners,面试中经常会被问到这个方法,一定要掌握。
父组件:
<template>
<div class="father">
<child
:age='age'
:sex='sex'
v-on:grandsonParame='grandsonParame'
/>
</div>
</template>
<script>
import child from './child.vue'
export default {
name:'father',
data(){
return{
age:'18',
sex:'男'
}
},
methods:{
grandsonParame(v){
console.log(`grandsonParame is ${v}`)
}
},
components:{child}
}
</script>
子组件:
<template>
<div class="child">
<Grandson v-bind="$attrs" v-on="$listeners"/>
<!--
用 v-bind="$attrs"的格式将父组件中所有往下传的参数传给自己的子组件 但不包含:class
用v-on="$listeners"的格式去接收自己子组件传给父组件的值
-->
</div>
</template>
<script>
import Grandson from './grandson.vue'
export default {
name:'child',
components:{Grandson}
}
</script>
孙组件:直接去取 a t t r s 得 值 , 里 面 包 含 第 一 级 组 件 传 的 所 有 参 数 , 并 且 通 过 t h i s . attrs得值,里面包含第一级组件传的所有参数,并且通过this. attrs得值,里面包含第一级组件传的所有参数,并且通过this.emit的方式把把当前位置的参数传给第一级组件,
<template>
<div class="grandson">
age:{{$attrs.age}}
sex:{{$attrs.sex}}
<p @click="handleClick">点击</p>
</div>
</template>
<script>
export default {
name:'grandson',
methods:{
handleClick(){
this.$emit('grandsonParame','come from grandson')
}
}
}
</script>