vue 隔代传值provide/inject方法如何使用?(响应式)

11 篇文章 0 订阅

vue 组件传值的方法有很多,但是项目中有些时候需要隔代传值,例如从曾祖父代网曾孙子代传值,普通的父子传值就比较麻烦,而使用vuex又不太划算,那么这个时候可以使用provide/inject方法;可以隔很多代往下传,但是必须是从上往下传
代码如下所示:
爷爷组件代码如下:

<template>
  <div class="home">
    <button @click="tap">爷爷组件传值</button>
    <child1></child1>
  </div>
</template>
<script>
import child1 from "./child1.vue";

export default {
  name: "Home",
  data() {
    return {
      msg: {
        aaa: "33",
      },
    };
  },
  provide() {
    return {
      //返回函数形式是为了响应式
      grandpaValue: () => this.msg,
    };
  },
  components: {
    child1,
  },
  methods: {
    tap() {
      this.msg = [1, 2, 3];
    },
  },
};
</script>
<style scoped>
.home {
  width: 800px;
  height: 800px;
  border: 1px solid blue;
}
</style>

父亲组件代码如下:

<template>
  <div class="box-wrap">
    <child11></child11>
    <child22></child22>
  </div>
</template>

<script>
import child11 from "./child1-1.vue";
import child22 from "./child1-2.vue";
export default {
  name: "",
  components: {
    child11,
    child22,
  },
  data() {
    return {};
  },
};
</script>

<style  scoped>
.box-wrap {
  width: 600px;
  height: 600px;
  border: 1px solid red;
}
</style>

孙子代码如下:

<template>
  <div class="box">
    {{val}}
  </div>
</template>

<script>
export default {
  inject: {
    grandpaValue: {
      // 键名
      from: "grandpaValue", // 来源
      default: "默认值", // 爷爷组件未传值,grandpaValue的默认值,爷爷传值的话grandpaValue是一个函数
    },
  },
  computed: {
    val() {
      //如果为函数,说明有值,就调用this.grandpaValue()取值,
      // 如果没有就直接返回this.grandpaValue默认值
      if (typeof this.grandpaValue === "function") {
        return this.grandpaValue();
      } else {
        return this.grandpaValue;
      }
    },
  },
  watch: {
    val() {
      console.log("数据改变时,孙子组件做的操作");
    },
  },
  data() {
    return {};
  },
};
</script>

<style  scoped>
.box {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值