$listeners

$listeners 用于多层次组件传递事件监听器,爷爷辈组件向父辈、孙子辈、曾孙子辈……组件传递事件(与 $attrs 不同,不存在半路被拦截的情况)

写法如下:(注:v-on 不能用简写 @,虽然不报错,但是也不生效)

<grand-son v-on="$listeners" />

面继续使用 爷爷-> 父亲 -> 孙子 的栗子:

爷爷(GrandFather)给父亲(Father)绑定一个 click 事件

父亲通过点击 div 触发 click 事件,同时向孙子(GrandSon)传递 $listeners

<!-- GrandFather.vue -->
<template>
  <div>
    GrandFather:
    <father :msg1="msg1" :msg2="msg2" @click="handleClick" />
  </div>
</template>

<script>
import Father from './Father.vue'
export default {
  components: { Father },
  data() {
    return {
      msg1: 'msg1',
      msg2: 'msg2'
    }
  },
  methods: {
    handleClick() {
      console.log('trriger click')
    }
  }
}
</script>

<!-- Father.vue -->
<template>
  <div>
    <div @click="handleFatherClick">Father: {{ msg1 }}</div>
    <grand-son v-bind="$attrs" v-on="$listeners" />
  </div>
</template>

<script>
import GrandSon from './GrandSon.vue'
export default {
  components: { GrandSon },
  props: ['msg1'],
  methods: {
    handleFatherClick() {
      console.log('father click')
      this.$emit('click')
    }
  }
}
</script>

<!-- GrandSon.vue -->
<template>
  <div @click="handleSonClick">GrandSon: {{ msg1 }}{{ msg2 }}</div>
</template>

<script>
export default {
  props: ['msg1', 'msg2'],
  methods: {
    handleSonClick() {
      console.log('grandson click')
      this.$emit('click')
    }
  }
}
</script>

  1. 界面:在这里插入图片描述
  2. 点击 Father: msg1,控制台显示:在这里插入图片描述
  3. 点击 GrandSon: msg2,控制台显示:在这里插入图片描述
Logo

前往低代码交流专区

更多推荐