provide和inject

93 阅读1分钟

provide 提供

提供给外面的人用我这里的数据

<template>
  <div :class="`app theme-${themeName} fontSize-${fontSize}`">
    <Child1 />
    <button>x</button>
    <Child2 />
    <button>x</button>
    <Child3 />
    <button>x</button>
    <Child4 />
    <button>x</button>
    <Child5 />
    <button>x</button>
  </div>
</template>

<script>
import Child1 from "./components/Child1.vue";
import Child2 from "./components/Child2.vue";
import Child3 from "./components/Child3.vue";
import Child4 from "./components/Child4.vue";
import Child5 from "./components/Child5.vue";
export default {
  name: "App",
  // 我提供了一些方法给 inject用
  provide() {
    return {
      themeName: this.themeName,
      changesink: this.changesink,
      fontModo: this.fontModo,
    };
  },
  data() {
    return {
      themeName: "blue", // 'red'
      fontSize: "normal", // 'big' | 'small'
    };
  },
  methods: {
    changesink() {
      if (this.themeName === "blue") {
        this.themeName = "red";
      } else {
        this.themeName = "blue";
      }
    },
    fontModo(name) {
      if (["normal", "big", "size"].indexOf(name) >= 0) {
        this.fontSize = name;
      }
    },
  },
  components: {
    Child1,
    Child2,
    Child3,
    Child4,
    Child5,
  },
};
</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;
}
.app.theme-blue button {
  background: blue;
  color: white;
}
.app.theme-blue {
  color: darkblue;
}

.app.theme-red button {
  background: red;
  color: white;
}
.app.theme-red {
  color: darkred;
}
.app.fontSize-normal {
  font-size: 16px;
}
.app button {
  font-size: inherit;
}
.app.fontSize-size {
  font-size: 18px;
}
.app.font-big {
  font-size: 22px;
}
</style>

inject

provide 提供了一个数据给我用 我就可以注入更改对方的一些东西

<template>
  <div>
    <button @click="x">当前皮肤颜色{{ themeName }},换肤</button>
    <button @click="fontModo('big')"></button>
    <button @click="fontModo('normal')"></button>
    <button @click="fontModo('size')"></button>
  </div>
</template>
<script>
export default {
// 对方提供了一些东西给我用
  inject: ["themeName", "changesink", "fontModo"],
  methods: {
    x() {
      console.log("x");
      this.changesink();
    },
  },
};
</script>