vue 朝花夕拾系列(6)- 组件通信$attrs/$listeners

vue 朝花夕拾系列(6)主要收录的就是vue组件间通信的几种方式,如
1.props、$emit/$on
2.vuex
3.$parent/$children
4.$refs
5.$root
6.$attrs/$listeners
7.provide/inject
8.中央事件bus(eventBus)
9.路由传参

本文主要阐述第六种:通过$attrs/$listeners获取没有在组件props属性中声明的属性和绑定在组件上的事件对象的方式完成数据通信…

$attrs/$listeners

$attrs

$attrs传值时是不会传递class和style以及已经被props接收的值的

场景:如果父传子有很多值,那么在子组件需要定义多个 props
解决:attrs获取子传父中未在 props 定义的值

  • father ===> child ===> grand-child 这种组件props下发
  • 通过在child组件中定义需要给child组件的width属性
  • $attrs就剩下需要传给grand-child孙子组件的数据
  • 没有定义native的非原生事件会被$listeners层层传递
1
2
3
4
5
6
7
// 父组件
<child title="这是标题" width="80" height="80" imgUrl="imgUrl"/>

// 子组件
mounted() {
console.log(this.$attrs) //{title: "这是标题", width: "80", height: "80", imgUrl: "imgUrl"}
},
  • 相对应的如果子组件定义了 props,打印的值就是剔除定义的属性
1
2
3
4
5
6
7
8
9
10
11
12
13
// child组件
<template>
<grand-child :attrs="$attrs"/>
</template>
props: {
width: { // --------------------定义了width
type: String,
default: ''
}
},
mounted() {
console.log(this.$attrs) //{title: "这是标题", height: "80", imgUrl: "imgUrl"} $attrs里面就没有width了
}

$listeners

$listeners里存放的是父组件中绑定的非原生事件

  • 使用.native修饰符的事件,不会体现在$listeners属性上。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//  father组件(App.vue)
<template>
<div id="app">
<child :username="username" :age="age" v-on:test1="onTest1" v-on:test2="onTest2"> //此处监听了两个事件,可以在B组件或者C组件中直接触发
</child>
</div>
</template>
<script>
import Child from './Child.vue';
export default {
data() {
return {
username:'pis',
age:18,
job:'developer'

};
},
components: { Child },
methods: {
onTest1() {
console.log('test1 running...');
},
onTest2() {
console.log('test2 running');
}
}
};
</script>

// children组件(Child.vue)
<template>
<div class="child">
<p>in child:</p>
<p>props: {{userName}}</p> // pis
<p>$attrs: {{$attrs}}</p> // 18 developer
<hr>
<!-- grandChild组件中能直接触发test的原因在于 child组件调用grandChild组件时 使用 v-on 绑定了$listeners 属性 -->
<!-- 通过v-bind 绑定$attrs属性,grandChild组件可以直接获取到father组件中传递下来的props(除了child组件中props声明的) -->
<grand-child v-bind="$attrs" v-on="$listeners" />
</div>
</template>
<script>
import grandChild from './grandChild.vue';
export default {
props: ['userName'],
data() {
return {};
},
inheritAttrs: false,
components: { grandChild },
mounted() {
this.$emit('test1'); // 这里触发test1的事件在father组件中打印
}
};
</script>

// grandChild 组件 (grandChild.vue)
<template>
<div class="grandChild">
<p>in grandChild:</p>
<p>props: {{age}}</p> // 18
<p>$attrs: {{$attrs}}</p> // developer
<hr>
</div>
</template>
<script>
export default {
props: ['age'],
data() {
return {};
},
inheritAttrs: false,
mounted() {
this.$emit('test2'); // 这里通过$listeners获取到test1和test2的事件,触发test2的事件在father组件中打印
}
};
</script>

参考链接

Vue 新增的$attrs与$listeners的详解
Vue 开发必须知道的 36 个技巧

初到贵宝地,有钱的给个钱场,没钱的挤一挤给个钱场