# mixins 混入

  • https://cn.vuejs.org/v2/guide/mixins.html
  • 作用:减少data、methods、钩子的重复
const log = {
  data() {
    return {
      name: undefined,
      time: undefined
    };
  },
  created() {
    if (!this.name) {
      throw new Error("need name");
    }
    this.time = new Date();
    console.log(`${this.name}出生了`);
  },
  beforeDestroy() {
    const now = new Date();
    console.log(`${this.name}死亡了,共生存了 ${now - this.time} ms`);
  }
};
export default log;
<template>
  <div>Child1</div>
</template>

<script>
import log from "../mixins/log.js";
export default {
  data() {
    return {
      name: "Child1"
    };
  },
  mixins: [log]
};
</script>

# extends 继承

  • 作用: 类似mixins,形式不同
import Vue from 'vue'
import log from "./mixins/log.js"
const MyVue = Vue.extend({
  mixins:[log]
})
export default MyVue;
<template>
  <div>Child1</div>
</template>

<script>
import MyVue from "../MyVue.js";
export default {
  data() {
    return {
      name: "Child1"
    };
  },
  extends:MyVue
};
</script>

# provide、inject

  • https://cn.vuejs.org/v2/api/index.html#provide-inject
  • 作用:大范围、隔N代共享信息
provide:Object | () => Object
inject:Array<string> | { [key: string]: string | Symbol | Object }
<template>
  <div :class="`app theme-${themeName} fontSize-${fontSizeName}`">
    <Child1/>
  </div>
</template>

<script>
import Child1 from "./components/Child1.vue";
export default {
  name: "App",
  provide() {
    return {
      themeName: this.themeName,
      changeTheme: this.changeTheme, 
      changeFontSize: this.changeFontSize
    };
  },
  data() {
    return {
      themeName: "blue", // 'red'
      fontSizeName: "normal" // 'big' | 'small'
    };
  },
  methods: {
    changeTheme() {
      if (this.themeName === "blue") {
        this.themeName = "red";
      } else {
        this.themeName = "blue";
      }
    },
    changeFontSize(size) {
      if (["normal", "big", "small"].indexOf(size) === -1) {
        throw new Error(`wront size: ${size}`);
      }
      this.fontSizeName = size;
    }
  },
  components: {
    Child1
  }
};
</script>
<template>
  <div>
    Child 
    <div>
      <button @click="changeTheme">换肤</button>
      <button @click="changeFontSize('big')">大字</button>
      <button @click="changeFontSize('small')">小字</button>
      <button @click="changeFontSize('normal')">正常字</button>
    </div>
  </div>
</template>

<script>
  export default {
    inject: ["themeName", "changeTheme", "changeFontSize"]
  };
</script>