Vue中 $attrs 和 $listeners 的用法

$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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值