vue组件通信,祖父级组件向孙子级组件传值,使用provide、inject

 1、上代码:

(1)祖父级组件parent的代码:

<!--
  文件描述:祖先级组件
  创建时间:2019/12/28 15:30
-->
<template>
  <div class="" style="width: 900px;height: 600px;background-color: #d6e7ff;padding: 20px;">
    <span style="font-size: 20px;font-weight: bold;">祖先级组件:father</span>
    <br>
    传给孙子级组件G的参数【toGdata】:{{toGdata}}<br>
    <input type="text" v-model="toGdata.name">
    <div>
      <childrenA></childrenA>
      <childrenB></childrenB>
      <childrenC></childrenC>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
// 例如:import 《组件名称》 from '《组件路径》';
import childrenA from './childrenA'
import childrenB from './childrenB'
import childrenC from './childrenC'

export default {
  name: 'father',
  provide () {
    return {
      toGdata: this.toGdata
    }
  },
  // import引入的组件需要注入到对象中才能使用
  components: {
    childrenA,
    childrenB,
    childrenC
  },
  data () {
    // 这里存放数据
    return {
      toGdata: { name: '李四' }
    }
  }
}
</script>

(2)儿子级组件C的代码:

<template>
  <div class="" style="float: left;margin: 10px;width: 250px;height: 500px;background-color: #eeff85;padding: 20px;">
    <span style="font-size: 18px;font-weight: bold;">儿子级组件C:childrenC</span>
    <div>
      <childrenF></childrenF>
      <childrenG></childrenG>
    </div>
  </div>
</template>

(3) 孙子级组件G的代码:

<!--文件描述:孙子级组件G
  创建时间:2019/12/28 15:37-->
<template>
  <div class="" style="float: left;margin: 10px;width: 200px;height: 200px;background-color: #ff00de;padding: 20px;color:#fff;">
    <span style="font-size: 14px;font-weight: bold;color:#fff;">孙子级组件G:childrenG</span>
    <div style="color:#0009ff;">
      接受来自祖父级组件parent的数据【toGdata】:{{toGdata}}
      <input type="text" v-model="fromParentData.name">
    </div>

  </div>
</template>

<script>
export default {
  name: 'childrenA',
  inject: ['toGdata'],
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      fromParentData: this.toGdata
    }
  }
}
</script>

注意: 这里不论子组件嵌套有多深, 只要调用了 inject  那么就可以注入  provide  中的数据,而不局限于只能从当前父组件的props属性中回去数据

2、传递参数为值类型(基本类型),接受参数的组件中不能进修改,传递对象或者数组,可以直接进行修改,并且可以影响祖先级组件

    (1)toGdata传值改为:String,在孙子级组件G中直接修改则报错:

    在祖父级组件parent中直接修改,没有传递到孙子级组件G:

(2)toGdata传值改为:Object,在孙子级组件G中直接则对应的祖先级组件数据也会受到影响,原因还是堆和栈储存数据的问题:

3、结论:在简单的功能模块,可以通过传递对象实现跨级组件通信,复杂的功能模块不建议使用,因为传递的数据,如果其他的儿子级组件,其他儿子级组件的孙子级组件也在使用的话,会造成数据的混乱,甚至无法理解数据是在哪里变化的,排查故障艰难。跨级组件通信可以定义一个中央事件总线(eventBus),但是更复杂的系统,还是建议使用vuex。

猜你喜欢

转载自www.cnblogs.com/pangchunlei/p/12112318.html