$listeners


包含了父作用域中的 (不含 .native 修饰器的) 所有v-on 事件。它可以通过 v-on=”$listeners” 传入内部组件——在创建更高层次的组件时非常有用

用法:

// index.vue
<template>
  <div>
     <child :name="testName" data-name="TEST001" @GetMsg="testMsg" />
  </div>
</template>
<script>
import { Component, Vue, Prop } from 'vue-property-decorator';
import child from './child.vue';
@Component({
  components: {
    child,
  },
})
export default class indexVue extends Vue {
  testName = 'Test101';

  testMsg(info) {
    console.log(info);
  }

}
</script>
// child.vue
<template>
  <div>
    <grandChild v-bind="$props" v-on="$listeners" />
  </div>
</template>
<script>
import { Component, Vue, Prop } from 'vue-property-decorator';
import grandChild from './grandChild.vue';
@Component({
  components: {
    grandChild,
  },
})
export default class AAChild extends Vue {
  @Prop() name;
}
</script>
// grandChild.vue
<template>
  <div @click="dddo">3333</div>
</template>
<script>
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component()
export default class grandChild extends Vue {
  @Prop() name;
  dddo() {
    this.$emit('GetMsg', 'TTND');
  }
}
</script>

点击3333的div标签,控制台输出了TTND

Vue3取消了$listeners

Vue3 已经不支持 $listeners 了

Vue2 的 $listeners 在 Vue3 中是合并到了 $attrs 里。

用法:

// index.vue
<template>
  <Child @call="handleEmit" />
</template>
<script>
    ...
      handleEmit() {
        console.log('hahaha')
      }
    ...
</script>
// Child.vue
<template>
   <Grandchild v-bind="$attrs" />
</template>
<script>
    ...
     setup(props, { attrs }) {
        console.log(attrs) 
        // 可以看到 Parent 传入的 call 事件,且前面加上了 on,变成了 onCall
      }
    ...
</script>
// Grandchild.vue
<template>
  <button @click="handleClick">Clikc</button>
</template>
<script>
    ...
    emits: ['call'],
    setup(props, { emit}) {
    return {
      handleClick() {
        emit('call') 
        // 成功触发 Parent 里面的 call 事件回调,在控制台打出 hahaha
      }
    }
    ...
</script>

Logo

前往低代码交流专区

更多推荐