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>
