在vue中经过使用$attrs实现组件之间的数据传递

组件之间传递数据的方式有不少种,之因此有这么多种方式,是为了知足在不一样场景不一样条件下的使用。javascript

通常有三种方式:html

  1. 经过 props 的方式向子组件传递(父子组件)vue

  2. vuex 进行状态管理java

  3. 非父子组件的通讯传递 Vue Event Bus,使用Vue的实例,实现事件的监听和发布,实现组件之间的传递vuex

本文介绍的是使用$attrs的方式。api

这是$attrs的官网api https://cn.vuejs.org/v2/api/#vm-attrside

这个api是在2.4版本中添加的,那么为何要添加这个特性呢?

看看官网是怎么解释的ui

包含了父做用域中不做为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。google

当一个组件没有声明任何 prop 时,这里会包含全部父做用域的绑定 (class 和 style 除外),spa

而且能够经过 v-bind="$attrs" 传入内部组件——在建立高级别的组件时很是有用。

第一次看的话真是不容易看懂,这里是既包含用法又隐晦的说明了为何使用,仍是我来解释一下吧。

意思就是:$attrs 能够收集父组件中的全部传过来的属性除了那些在组件中没有经过 props 定义的。

引伸说明一下,若是组件的嵌套层级有点深但又不那么深,好比三层。

咱们若是使用props的话,最里面的组件想要获取最外层组件的数据,就要经过中间的组件的props来传递,

可是这个props对于中间的这个组件没啥用处,它就是作了一个桥梁而已。咱们平时写代码时候其实常常碰到

这种场景,写起来有时候以为挺烦的。因此就有了这个$attrs来帮助咱们,没必要在中间组件中写props就可让

最里面的组件拿到最外面组件传进来的数据。

那么,具体怎么使用呢?

看看下面的代码吧,很简单就懂了

准备三个组件

里面的代码以下

//grandfather
<template>
  <div style="background: blue">
    father in grandfather
    <father :father-age="50" :child-time="`${time}`"></father>
  </div>
</template>
<script>
import father from './father'
export default {
  components: {
    father
  },
  data () {
    return {
      time: new Date().getTime()
    }
  }
}
</script>

//father
<template>
  <div style="background: red">
    child in father
    <div>
      <span>father age:</span>{{fatherAge}}
    </div>
    <child v-bind="$attrs"></child>
  </div>
</template>
<script>
import child from './child'
export default {
  components: {
    child
  },
  props: {
    fatherAge: {
      type: Number,
      default: 0
    }
  }
}
</script>

//child<template>
  <div style="background: green">
    <div>child</div>
    <div>time: {{childTime}}</div>
  </div>
</template>
<script>
export default {
  props: {
    childTime: {
      type: String,
      default: ''
    }
  }
}
</script>

须要从爷爷组件直接传给子组件的数据,不要在父组件中的props中声明。

在子组件上经过v-bind的方式就能够把父组件中未声明而子组件须要从爷爷组件中获取的数据传给子组件。

固然,子组件props确定是要声明的,仍是props的用法啦。

最后须要注意的一点是,$attrs是要配合inheritAttrs: false使用的哦,具体为何能够看下官网教程https://cn.vuejs.org/v2/guide/components-props.html#%E9%9D%9E-Prop-%E7%9A%84%E7%89%B9%E6%80%A7禁用特性教程这一小节,可是其实讲的也是不清楚,建议google一下吧。

相关文章
相关标签/搜索