Mixins

可以将公共的数据、方法和生命周期函数声明在混入中,方便管理与统一修改。如果是全局混入,可以在任何的组件中直接使用混入中的数据或方法,如果是局部混入,哪个组件引入该混入,就可以在哪个组件中使用该混入中的数据和方法

同一个生命周期,mixins中的会比组件中的先执行。

全局混入

1// 必须声明在 main.js 中,且在 new Vue 对象之前
2import Vue from 'vue'
3import App from './views/indexView.vue'
4import router from './router'
5import store from './store'
6
7Vue.config.productionTip = false
8
9Vue.mixin({
10	data(){
11		return {}
12	},
13	methods:{}
14})
15
16new Vue({
17  router,
18  store,
19  render: h => h(App)
20}).$mount('#app')

局部混入

  • 导出mixins
1// src/mixins/index.js
2export default {
3  created() {
4    console.log("这里是Mixins触发的created");
5  },
6};
  • 引用mixins
1<template>
2  <div></div>
3</template>
4
5<script>
6import mixins from "@/mixins";
7export default {
8  data() {
9    return {};
10  },
11  // 局部混入需要注册
12  mixins: [mixins],
13  created() {
14    console.log("我是组件触发的created");
15  },
16};
17</script>