vue之provide和inject

官方说:

当我们需要从父组件向子组件传递数据时,我们使用 props。想象一下这样的结构:有一些深度嵌套的组件,而深层的子组件只需要父组件的部分内容。在这种情况下,如果仍然将 prop 沿着组件链逐级传递下去

个人理解:

在祖先组件中定义provide(提供)给后代组件的数据或方法,在后代组件中可以通过inject(接受)提供的数据或方法

举个栗子,
想做一个孙子组件刷新爷爷组件的功能

爷爷组件定义provide的data和方法

//祖先组件
<!--
 * @Author: your name
 * @Date: 2021-05-18 09:32:56
 * @LastEditTime: 2021-06-30 11:47:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vuedemo/src/App.vue
-->
<template>
  <div id="app">
    <el-container>
      <el-header> <nav-new></nav-new></el-header>
      <el-main> <router-view v-if="isRouterAlive"/></el-main>
      <div class="">
        <el-button @click="changeName()">点击</el-button>
      </div>
    </el-container>
  </div>
</template>

<script>
import Vue from "vue";
import NavNew from "./components/Navbar";
export default {
  name: "App",
  provide() {
    return {
      reload: this.reload,
      name: this.name,
    };
  },
  data() {
    return {
      isRouterAlive: true,
      name: "wht",
    };
  },

  methods: {
    //重新加载
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(function() {
        this.isRouterAlive = true;
      });
    },
    changeName() {
      this.name = "瀚海云涛";
      console.log(this.name);
    },
  },
  components: {
    NavNew,
  },
};
</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>

子组件引入孙组件

<!--
 * @Author: your name
 * @Date: 2021-06-30 11:14:07
 * @LastEditTime: 2021-06-30 11:28:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vuedemo/src/web/proInject.vue
-->
<!--  -->
<template>
  <div class="">
    <p>provide和inject的使用</p>
    <grand-son></grand-son>
  </div>
</template>

<script>
import GrandSon from "@/components/GrandSon.vue";
export default {
  components: {
    GrandSon,
  },
  data() {
    return {};
  },
};
</script>
<style scoped></style>

孙组件用inject接受data和函数

<!--
 * @Author: your name
 * @Date: 2021-06-30 11:07:28
 * @LastEditTime: 2021-06-30 11:36:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vuedemo/src/components/GrandSon.vue
-->
<!--  -->
<template>
  <div class="">
    孙子组件控制爷爷组件刷新
    <el-button @click="toRefresh">点我</el-button>
    <p>爷爷组件定义的name值:{{ name }}</p>
  </div>
</template>

<script>
export default {
  inject: ["reload", "name"],
  data() {
    return {
      name: this.name,
    };
  },
  methods: {
    toRefresh() {
      this.reload();
    },
  },
};
</script>
<style scoped></style>

posted @ 2021-08-25 18:08  瀚海云涛  阅读(186)  评论(0编辑  收藏  举报