mixins(组件混入)

一、理解组件混入

vue的组件混入是为了交流组件之间的共性,提高代码复用效率。

1.定义一个多组件公用的方法
const myMixin = {
     methods: {
        formateDate:function(seconds,type){
            let time = new Date(seconds);
            let year = time.getFullYear();
            let month = time.getMonth()+1;
            let day = time.getDate();
            let hours = time.getHours();
            let minute = time.getMinutes();
            let second = time.getSeconds();
            switch(type){
                case 0 :return [year,month,day].map(this.dateRule).join('-'); break;
                case 1 :return [year,month,day].map(this.dateRule).join('-')+' '+
                [hours,minute,second].map(this.dateRule).join(':') ; break;
            }
        },
        dateRule:function(e){
            return e<10?0+''+e:e
        },
    }
}
export default myMixin 
2.在需要的组件上调用混入该方法
import myMixin from '../mixins/myMixin'
export default {
  name: 'HelloMixin',
  created(){
    //调用混入的方法
    console.log(this.formateDate(new Date(),0)) //2018-05-08
  },
  mixins: [myMixin],
}

二、键值冲突

当混入的键与引入键冲突时以组件内的键不会被替换。

var mixin = {
  methods: {
    sayHello: function () {
      console.log('我是混入方法sayHello')
    },
    sayGoodBy: function () {
      console.log('再见混入')
    }
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    sayHello: function () {
      console.log('我是组件那内的SayHello')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})
vm.sayHello() // => "我是组件那内的SayHello'"
vm.sayGoodBy() // => "bar"
vm.conflicting() // => "from self"

你可能感兴趣的:(mixins(组件混入))