The use of attrs and listeners in vue2 (component communication)
Vue2.4.0 new $attrs
and $listener
attribute
-
attrs
When a component does not declare any props,
$attrs
it will contain all parent scope bindings (except class and style), and can bev-bind="$attrs"
passed to internal components, generally used on child elements of child components -
listener
Contains v-on event listeners from the parent scope (without the .native decorator). It can be
v-on="$listeners"
passed to internal components via
<template>
<div class="page-all">
a-page
<B :msg1="msg1" :msg2="msg2" @method1="handleClick" @method2="handleClick"></B>
</div>
</template>
<script>
import B from "./B.vue"
export default {
name: "A",
data() {
return {
msg1: "msg1",
msg2: "msg2",
}
},
components: {B},
methods: {
handleClick() {
console.log('a click')
}
},
mounted() {},
}
</script>
<template>
<div class="page-all">
b-page
<p>$attrs: {
{ $attrs }}</p>
<div @click="handleAClick">handleAClick: {
{ msg1 }}</div>
<C v-bind="$attrs" v-on="$listeners"></C>
</div>
</template>
<script>
import C from "./C.vue"
export default {
name: "B",
props: ['msg1'],
data() {
return {}
},
components: {C},
methods: {
handleAClick() {
console.log('b click')
this.$emit('method1')
}
},
mounted() {},
}
</script>
<template>
<div class="page-all">
c-page
<p>$attrs: {
{ $attrs }}</p>
<div @click="handleCClick">handleCClick: {
{ msg1 }}{
{ msg2 }}</div>
</div>
</template>
<script>
export default {
name: "C",
props: ['msg1', 'msg2'],
data() {
return {}
},
components: {},
methods: {
handleCClick() {
console.log('c click')
this.$emit('method2')
}
},
mounted() {},
}
</script>
-
Summarize
$attrs
props
It is to send the parent component to the grandchild component that is not receivedlistener
by the component , but to@方法
inherit the parent component to the grandchild component