vue中$listeners的使用

定义:

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

理解:

所谓$listeners其实就相当于一个中间件,当出现多级组件嵌套时,孙组件想传递数据给爷组件,那么就需要在父组件中给孙组件设置v-on="$listeners",然后通过@键的方式监听孙组件传递过来的数据。

为什么要用$listeners?

因为$listeners可以很好的解决在多级组件嵌套中,组件C传给组件A传递数据的问题。

$attrs和$listeners的使用场景:

对一些UI库进行二次封装用,比如element-ui,里面的组件不能满足自己的使用场景的时候,会二次封装,但是又想保留他自己的属性和方法,那么这个时候时候$attrs和$listners是个完美的解决方案。

简单的例子,对el-button二次封装

<template>
    <el-button v-on="$listeners" v-bind="$attrs" :loading="loading" @click="myClick">
        <slot></slot>
    </el-button>
</template>

<script>
export default {
    name: 'mButton',
    inheritAttrs: false,
    props: {
        debounce: {
            type: [Boolean, Number]
        }
    },
    data() {
        return {
            timer: 0,
            loading: false
        }
    },
    methods: {
        myClick() {
            if (!this.debounce) return
            this.loading = true
            clearTimeout(this.timer)
            this.timer = setTimeout(
                () => {
                    this.loading = false
                },
                typeof this.debounce === 'boolean' ? 500 : this.debounce
            )
        }
    }
}
</script>