vue mixins

转自:https://segmentfault.com/a/1190000009875015#articleHeader2

1.场景

假设我们有几个不同的组件,它们的工作是切换状态布尔、模态和工具提示。这些提示和情态动词不有很多共同点,除了功能:他们看起来不一样,他们不习惯相同,但逻辑是相同的。

//弹框
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
  }
};

用mixins引入toggle功能相似的js文件,进行混合使用

2.可以合并生命周期

//mixin
const hi = {
  mounted() {
    console.log('this mixin!')
  }
}

//vue组件
new Vue({
  el: '#app',
  mixins: [hi],
  mounted() {
    console.log('this Vue instance!')
  }
});

//Output in console
> this  mixin!
> this Vue instance!

先输出的是mixins的数据

3、可以全局混合(类似已filter)

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

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

会在每一个组件中答应周期中的log,同时里面的方法,类似于vue的prototype添加实例方法一样。

var install = function (Vue, options) {
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }
  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })
  // 3. 注入组件
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })
  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (options) {
    // 逻辑...
  }
}

猜你喜欢

转载自blog.csdn.net/leverage2009/article/details/80756701
今日推荐