说下$attrs和$listeners的使用场景
-
组件传值的时候会用到 爷爷在父亲组件传递值,父亲组件会通过$attrs获取到不在父亲props里面的所有属性,父亲组件通过在孙子组件上绑定$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>