运用$attrs和$listeners以及inheritAttrs用法

组件关系图:

父组件:listeners.vue

子组件:listenersSon.vue

孙组件:listenersGrandson 

适用场景:

一般父子组件传值用props,类似父子孙组件这种,若用props就要父组件传给子组件,子组件再传给孙组件,一旦这种组件的嵌套增多,数据容易混乱,不易维护和使用,此时,$attrs和$listeners以及inheritAttrs的使用就会显得简洁明了

官网上对于inheritAttrs的说明:API — Vue.jsVue.js - The Progressive JavaScript Frameworkhttps://cn.vuejs.org/v2/api/#inheritAttrs

实例

父组件传递label和msg两个属性值

父组件

<div>
    <h1>listeners</h1>
    <listenersSon @btnClick="fromGrandson" label="名称" msg="儿孙们真棒!"></listenersSon>
  </div>

 fromGrandson(data) {
      console.log("来自孙孙的信息", data);
    }

 子组件HTML:

<template>
  <div>
    <h1>listenersSon</h1>
    <listenersGrandson v-bind="$attrs" v-on="$listeners"></listenersGrandson>
  </div>
</template>

子组件JS :

<script>
import listenersGrandson from "./listenersGrandson";
export default {
  // inheritAttrs: false,
  components: { listenersGrandson },
  // props: ["msg"],
  data() {
    return {};
  },
  mounted() {
    console.log("子组件:$attrs", this.$attrs);
    console.log("子组件:msg", this.msg);
  }
};
</script>

 孙组件:

<template>
  <div>
    <h1>listenersGrandson</h1>
    <div @click="toGrandfather">传递给俺爷爷</div>
  </div>
</template>
<script>
export default {
  inheritAttrs: false,
  props: ["msg"],
  data() {
    return {
      isShow: true
    };
  },
  mounted() {
    console.log("孙组件:$attrs", this.$attrs);
    console.log("孙组件:msg", this.msg);
  },
  methods: {
    toGrandfather() {
      this.$emit("btnClick", "爷爷你好,这是俺给爷爷的数据");
    }
  }
};
</script>

inheritAttrs默认为true,子组件不设置props,孙组件设置props值 msg,子组件根节点上 label和msg直接编译成对应的HTML挂载在dom上;孙组件由于设置了msg的props值,只有label挂载在dom上,能从$attrs拿到绑定的值,效果如下图所示

inheritAttrs默认为false,子组件不设置props,孙组件设置props值 msg,label和msg都未挂载在dom上,能从$attrs拿到绑定的值,效果如下图所示

$listeners

孙组件向上emit的事件btnClick,无需通过子组件中转,父组件通过回调,直接拿到孙孙的数据,

结论:

使用范围:适用于跨组件通信的场景

总结:

1、inheritAttrs为false时,除了props的属性外,其余绑定的属性都挂载在组件根节点上

2、inheritAttrs设置为true或者false,都能通过$attrs获取组件的属性值(除了props的属性外)

3、$listeners,孙组件向上emit的事件,达到和父组件的通信

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值