备注:此属性是2.4.0 新增
组件的嵌套关系如下:
grandpa>father>son
1.vm.$attrs:
使用场景:孙子组件想要拿到爷爷组件的信息且不借助于于vuex的情况下可以利用此来实现
(1)描述:
vm.$attrs
在子组件不通过props取数据的情况下:
1.通过this.$attrs可以拿到父组件传递过来的所有数据,
2.爸爸组件上添加v-bind="$attrs",那么孙子组件中就可以访问到爷爷组件传递给爸爸组件,以及爸爸组件传给儿子组件的所有数据,
通过props接收的数据项无法在$attrs中获取到。
备注:class,style除外
(2)实例如下:
//grandpa.vue
<div>
<father jj="sjhfjds" class="dddd" style="height:100px"><father>
</div>
//father.vue
<template>
<div>
<son v-bind="$attrs" kkk="易洋千玺><son>
</div>
<template>
.....
mounted(){
console.log(this.$attrs); //jj: "sjhfjds"
}
//son.vue
mounted(){
console.log(this.$attrs); //kkk:"易洋千玺",jj: "sjhfjds"
}
2.$listeners
(1)使用场景,孙子组件传递信息给爷爷组件
(2)实例如下:
//孙子组件
<template>
<div @click.stop="hanldeThing">测试</div>
</template>
...
methods:{
hanldeThing(){
this.$emit('yyqx','易洋千玺‘);
}
}
//爸爸组件
<template>
<son v-on="$listeners"></son>
</template>
//爷爷组件:
<template>
<father @yyqx="showInfo"></father>
</template>
...
methods:{
showInfo(data){
console.log(data);//易洋千玺
}
}