饥人谷技术博客前端必备

vue中的$attrs对比props

2021-07-07  本文已影响0人  fanlelee
首先需要弄清楚的是:

在vue中父类在使用子类组件时,默认将绑定事件传给了子类组件的根元素
例:
有这样一个组件:

<template>
  <div>
    <button><slot/></button>
  </div>
</template>

使用该组件:

 <Button @click="xxx" @focus="yyy" size="small">I'm button</Button>

以上例子中,click、focus事件的作用范围是组件的根结点<div>,而通常,我们是想在<button>上绑定事件,所以要取消事件,然后再手动绑定到<button>上。

  1. 在子类组件的选项中设置:inheritAttrs:false,组件的根元素就会取消继承,绑定事件无效。
  2. 事件无效后,需要将事件手动绑定到想要绑定的组件某元素上,即:
    <div><button v-bind="$attrs"></button></div>
  3. $attrs
    • $attrs:包含了在使用组件时设置的所有属性,包括绑定事件;
    • $attrs等同于setup里面的context.attrs
      v-bind="$attrs中,$attrs包含了size和绑定事件,需要分离出来:
      setup(props, context){
        const {size, ...rest} = context.attrs
        return {size, rest}
      }
    
    那么:v-bind="rest"
    <div><button v-bind="rest"></button></div>
    

props和$attrs区别

通过以上,props和$attrs的区别显而易见。

上一篇 下一篇

猜你喜欢

热点阅读