vue中的$attrs 与 $listeners 多级组件间的信息传递

1.应用场合

多层级组件之间传参可以使用$attrs, 如果使用普通的父子组件传参prop$emit,每一级组件都需要进行接收,然后向下传递,就很麻烦。

在使用$attrs时,如果组件中不使用props进行接收,这些参数将会作为此组件的HTML元素特性。如果这个组件中使用了props进行了接收,那么被接收的参数将不会向下传递。

inheritAttrs: false的含义是不希望本组件的根元素继承父组件的attribute,同时父组件传过来的属性(没有被子组件的props接收的属性),也不会显示在子组件的dom元素上,但是在组件里可以通过其$attrs可以获取到没有使用的注册属性。

$attrs 是传递参数变量的

$listenters 是传递函数的

2.直接上代码 

组件结构为 grandFatherView > fatherView > childView

grandFatherView组件中:

<template>
  <div class='grand-father-view'>
    <fatherView :row="row" :column="column" @friendly="friendly" @diss="diss"> </fatherView>
  </div>
</template>

<script>
import fatherView from './fatherView.vue'
export default {
 components:{ fatherView },
 data() {
    return {
      isOpen: false,
      row: {name: 'nicholas', age: 23},
      column:{sex: '男', id : 12},
      diss: ()=>{
        console.log("diss")
      },
      friendly: ()=>{
        console.log("friendly")
      }
    }
  }
}
<script>

fatherView组件中,拦截row参数,column将通过$attrs继续传递;

<template>
  <div class='father-view'>
    <p>{{ row.name }}</p>
    <p>{{ row.age }}</p>
    <childView v-bind="$attrs" v-on="$listeners"> </childView >
  </div>
</template>

<script>
import childView from './childView .vue'
export default {
 inheritAttrs: true, // 浏览器F12调试可以看到 此组件的根元素,:column="[objcet, object]"
 components:{ childView  },
 data() {
    return { }
 },
 props:{
    row: {
        type: object,
        default: () => {}
    }
 },
 mounted(){
     this.$listeners.friendly()
 }
}
<script>

childView组件中,接收column参数

<template>
  <div class='child-view'>
    <p>{{ column.sex }}</p>
    <p>{{ column.id }}</p>
  </div>
</template>

<script>
export default {
 data() {
    return { }
 },
 props:{
    column: {
        type: object,
        default: () => {}
    }
 },
 mounted(){
     this.$listeners.diss()
     this.$listeners.friendly()
 }
}
<script>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值