vue.js之多层父子组件通信方式一($attrs和$listeners)

多层父子组件通信通信方式一(爷爷和孙子通话)

  • vue.js之多层父子组件通信方式二(provide和inject)
  • $attrs,包含了父组件作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外);当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件。
  • $listeners,包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器,它可以通过v-on="$listeners" 传入内部组件。
  • 假如有组件A CompA(爷爷)、组件B CompB(爸爸)、组件C CompC(孙子),App.vue调用组件A,组件A调用组件B,组件B调用组件C,且组件A要给组件C(孙子)传数据,其中组件B(爸爸)也要收数据。

App.vue

<template>
  <div id="app">
    <CompA title="123"></CompA>
  </div>
</template>
<script>
 import CompA from "./components/CompA";
export default {
  name: 'App',
  components: {
    CompA,
  },
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

组件A

<template>
  <div>
    CompA
    <!-- 通过$attrs传给CompB,CompC -->
    <!-- $attrs收集属性 $listeners收集事件-->
    <CompB title="my name is CompA" v-bind="$attrs" v-on="$listeners"></CompB>
  </div>
</template>
<script>
import CompB from "./CompB";
export default {
  // 爷爷要给孙子CompA传话
  //和$attrs结合起来用
 inheritAttrs: false,  
  components: {
    CompB,
  },
  mounted () {
    //   attrs  如果没有在props里面定义的参数,都会到这里来
      console.log(this.$attrs);
      console.log(this);
  },
};
</script>
<style scoped>
</style>

组件B

<template>
    <div>
        CompB
        <CompC v-bind="$attrs"></CompC>
    </div>
</template>
<script>
import CompC from "./CompC";
    export default {
        components: {
            CompC,
        },
        mounted () {
            console.log(this.$attrs);
            console.log(this.$listener);
        },
    }
</script>
<style lang="scss" scoped>
</style>

组件C

<template>
    <div>
        CompC
        {{$attrs.title}}
    </div>
</template>
<script>
    export default {
        //收到了爷爷CompA说的话
        mounted () {
            console.log(this.$attrs);
        },
    }
</script>
<style lang="scss" scoped>
</style>

在这里插入图片描述

inheritAttrs 属性
  • inheritAttrs:false 是不允许组件绑定的未注册属性渲染到组件根节点上的,默认是true。
<template>
    <div>
        <button :disabled="$attrs.disabled">click</button>
    </div>
</template>
<script>
    export default {
        inheritAttrs: false,  
    }
</script>
<style lang="sass" scoped>
</style>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值