$attrs是捡props漏的;
$listeners的作用:grandson 的事件 = ChildDemo 的监听事件 eventBindOnB + 她本身 的监听事件 change
//父组件
<template>
<div class="index">
<ChildDemo
:one="myOne"
:two="myTwo"
:three="myThree"
@eventBindOnB="eventMethodInA"
/>
</div>
</template>
<script>
import ChildDemo from "./comps/childDemo.vue"
export default {
name: 'index',
components: {
ChildDemo
},
data() {
return {
myOne: 'myOne',
myTwo: 'myTwo',
myThree: 'myThree'
}
},
methods: {
eventMethodInA() {
console.log('我是在index中的方法');
}
}
}
</script>
<style>
.index {
width: 400px;
height: 300px;
border: 1px solid red;
margin: auto;
}
</style>
//子组件
<template>
<div>
<p>{{one}}</p>
<p>{{three}}</p>
<button @click="btnClick">我是childDemo</button>
<p>--------------------------------------------------------------</p>
<grandson
:coo="three"
msg="B 组件的配置,但是 C 组件没有定义"
v-bind="$attrs"
v-on="$listeners"
@change="eventMethodInB"></grandson>
</div>
</template>
<script>
import grandson from "./grandson"
export default {
name: 'ChildDemo',
components: {
grandson
},
props: ['one', 'three'],
created() {
console.log('childDemo', this.$attrs);//childDemo {two: 'myTwo'}
console.log('childDemo', this.$listeners);//childDemo {eventBindOnB: ƒ}
},
methods:{
eventMethodInB() {
console.log('我是childDemo的方法');
},
btnClick() {
this.$emit('eventBindOnB')// 触发 A 的监听事件
}
}
}
</script>
//孙组件
<template>
<div>
<button @click="triggerMethodInA">我是孙</button>
<p>{{$attrs.coo}}--{{msg}}--{{$attrs.two}}</p>
</div>
</template>
<script>
export default {
name: 'grandson',
props:['msg'],
created() {
console.log('grandson', this.$attrs);//grandson {coo: 'myThree', msg: 'B 组件的配置,但是 C 组件没有定义', two: 'myTwo'}
console.log('grandson', this.$listeners);//grandson {change: ƒ, eventBindOnB: ƒ}
},
methods: {
triggerMethodInA() {
this.$emit('change') //触发 B 的监听事件
this.$emit('eventBindOnB') // 触发 A 的监听事件
}
}
}
</script>