vue中实例属性--$attrs,$listeners

备注:此属性是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);//易洋千玺
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值