$attrs 和 $listeners


$attrs

  • 只读
  • 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。
  • 优点在于避免传多个参数时,都要声明到props的麻烦,可直接通过$attrs.xx展示数据。
// hello.vue
<diy-component @click="getClick" msg1="通过props" msg2="不通过props"></diy-component>

//diyComponent.vue
<template>
  <div>
    传递:{{$attrs}}
  </div>
</template>

<script>
export default {
  name: 'diyComponent',
  props: ['msg1'] //通过props传递值
}
</script>

页面显示为
在这里插入图片描述

$listeners

  • 只读
  • 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。
  • 简单说就是将父组件的所有监听器(监听事件),通过v-on="$listeners" 绑到目标子组件;使其子组件可以更方便的调用父组件的相关函数。
//hello.vue
 <diy-component ref="ttx" @click="clickMe"></diy-component>
 	// clickMe () {
    //   console.log('来自爸爸的点击')
    // }
//diyComponent.vue
<template>
  <div>
   	//点击子组件的button,调用的是组件根元素的clickMe方法
    <el-button v-on="$listeners">click</el-button>
  </div>
</template>

inheritAttrs(补充)

  • 如果你不希望组件的根元素继承特性,你可以在组件的选项中设置 inheritAttrs: false。
  • 通过实例属性 $attrs 可以让这些特性生效,且可以通过 v-bind 显性的绑定到非根元素上。
//hello.vue
<diy-component ref="ttx" @click="clickMe" msg1="通过props" msg2="不通过props" placeholder="nothing"></diy-component>

//diyComponent.vue
<template>
  <div>
    <div v-bind="$attrs">
      传递:{{$attrs}}
    </div>
    <el-button v-on="$listeners">click</el-button>
  </div>
</template>

<script>
export default {
  name: 'diyComponent',
  props: ['msg1'],
  inheritAttrs: false
}
</script>

在这里插入图片描述
inheritAttrs: false 隐藏了根元素上的属性;
v-bind="$attrs" 可将属性绑定到非根元素上。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值