vue中如何优雅实现爷孙组件的数据通信($attrs/$listeners)

$attrs和 $listeners如何使用呢?

  • $attrs是用来将数据从爷组件传递给孙组件的。(理解为之前的父传子)
  • $listeners是用来从孙组件中触发爷组件中事件的。(理解为之前的子传父)

$attrs的使用:

  • 孙子组件正常写功能代码,正常定义props 来接收数据,这里假设props里面定义了一个字符串类型的name。
  • 父组件使用 $attrs (v-bind=" $attrs")
  • 爷爷组件正常以前父传子的写法(:name=“name”)
    (这里需要注意的是父组件中不需要接收props,只要在孙组件中接收就可以。)
<!-- 在爷爷组件中(index.vue) -->
<Father :name="name"/>
<!-- 在父组件中(father.vue) -->
<Son v-bind="$attrs"/>
<!-- 在孙子组件中(son.vue) -->
<template>
    <div class="home">
    {
   
   {name}}
    </div>
</template>
<script>
export default {
      
      
    data() {
      
      
        return {
      
      };
    },
    props: {
      
      
        name: {
      
      
            default: String
        },
    },
};
</script>

$listeners的使用:

  • 在爷组件(index.vue)中,绑定事件。
  • 在父组件中,也是类似绑定事件,但是这里绑定的不是具体的事件,而是v-on=“$listeners”。
  • 在孙组件中,需要的时候触发( $emit)这个事件即可。
<!-- 在爷爷组件中(index.vue) -->
<Father :name="name" :newHome.sync="newHome" />
<!-- 在父组件中(father.vue) -->
<BaseButton  v-on="$listeners"></BaseButton>
<!-- 在孙子组件中(son.vue) -->
<template>
  <div class="base_button">
    <el-button @click="update">我是孙子组件</el-button>
  </div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    update() {
      
      
      const newHome = {
      
      
        name: "new",
      };
      this.$emit("update:newHome", newHome);
    },
  },
};
</script>

总结:

其实 $attrs和 $listeners相当于是一个中转,主要用在父亲组件上。爷组件和孙组件保持以前的使用即可!

猜你喜欢

转载自blog.csdn.net/pink_cz/article/details/126222186