$listeners
它可以获取父组件传递过来的所有自定义函数,如下:
// 父组件
<template><div class="a"><Child @abab="handleAbab" @acac="handleAcac"/></div>
</template><script>
import Child from './components/Child.vue';
export default {components: {Child},methods: {handleAbab(){},handleAcac(){}}
}
</script>
// 子组件
<template><div class="cc"></div>
</template><script>
export default {data(){return{count: 0}},created(){console.log(this.$listeners);}
}
</script>
看个例子
// 父组件
<template><div class="a"><Child @abab="handleAbab" @acac="handleAcac"/></div>
</template><script>
import Child from './components/Child.vue';
export default {components: {Child},methods: {handleAbab(count){console.log('收到',count);// 模拟处理return new Promise((resolve) => {setTimeout(() => {resolve("error");}, 3000);});},handleAcac(){}}
}
</script>
子组件需要等待父组件处理结束后再继续操作
template><div class="cc"><button @click="handleClick">click</button><div>{{ count }}</div></div>
</template><script>
export default {data(){return{count: 0}},methods:{async handleClick(){this.count++;if(this.$listeners.abab){const err = await this.$listeners.abab(this.count);console.log(err);}}}
}
</script>