vue mixin初识

理解:

总体来说,就是用于js代码的混合,和 css 里的 mixin 一个套路。
和component 对比,同样是作为 父组件的一部分。不同点是 父组件会将mixin内容 合并,即 父组件能得到 mixin的 属性和方法。
默认合并规则是,同名的都会以 父组件 为准。同名钩子,会先执行mixin的

var mixin = {
    methods: { foo: function () { console.log('foo') }, conflicting: function () { console.log('from mixin') } } }
var vm = new Vue({
    mixins: [mixin],
    methods: { bar: function () { console.log('bar') }, conflicting: function () { console.log('from self') } } })
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

使用场景举例:

两个页面的方法、数据极为相似,这个时候不要写两份了。就像less 里的mixin、

//弹框
const Modal = {
  template: '#modal',
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  },
  components: {
    appChild: Child
  }
}

//提示框
const Tooltip = {
  template: '#tooltip',
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  },
  components: {
    appChild: Child
  }
}


上面是一个弹框和提示框,如果考虑做2个组件,或者一个兼容另一个都不是合理方式。请看一下代码

const toggle = {
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  }
}

const Modal = {
  template: '#modal',
  mixins: [toggle],
  components: {
    appChild: Child
  }
};

const Tooltip = {
  template: '#tooltip',
  mixins: [toggle],
  components: {
    appChild: Child
  }
};

特例1:可以全局混合(类似已filter)

Vue.mixin({
  mounted() {
    console.log('hello from mixin!')
  },
  method:{
     test:function(){
     }
    }
})

new Vue({
  el: '#app',
  mounted() {
    console.log('this Vue instance!')
  }
})

特例2:想要自定义合并规则可以使用 Vue.config.optionMergeStrategies

 未验证,参考链接:https://cn.vuejs.org/v2/guide/mixins.html

原文地址:https://www.cnblogs.com/fan-zha/p/10842737.html