Fe-interview: [vue] 说下$attrs和$listeners的使用场景

Created on 22 Jun 2019  ·  5Comments  ·  Source: haizlin/fe-interview

[vue] 说下$attrs和$listeners的使用场景

vue

Most helpful comment

一般我对一些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>

All 5 comments

创建高级组件

组件传值,祖孙组件有跨度的传值。

组件传值的时候会用到 爷爷在父亲组件传递值,父亲组件会通过$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>

祖孙传值,这也太难了

Was this page helpful?
0 / 5 - 0 ratings