vue-mixins混入

85 阅读1分钟

组件里面如果有很多的配置是相同的,可以借助混合去复用

1.功能:可以把多个组件共用的配置提取成一个混入对象
2.使用方式:

第一步定义混合:
{ data(){....}, methods:{....} .... }
第二步使用混入:
全局混入:Vue.mixin(xxx)
局部混入:mixins:['xxx']

image.png

局部引入混入: 在需要的组件中引入,则该组件就能使用mixins里的配置

//重新开一个js文件(mixin)
export const hunhe = {
  methods: {
    showName() {
      alert(this.name)
    }
  },
  mounted() {
    console.log("nihao!!!")
  }
}

image.png

全局引入混合:

import Vue from "vue";
import App from './App.vue'

//在main.js文件中使用
import { hunhe } from "./mixin"
Vue.mixin(hunhe);

new Vue({
  render: h => h(App),
}).$mount('#app')

因为在全局注册了,所以此处注释掉也是可以使用的 image.png

使用全局mixin,所有的vm和vc都可以接收到里面的配置
输出总共是四个nihao!!!,因为总共有一个vm,三个vc(App,Students,School)

image.png