vue mixins组件复用的几种方式

  • 最近在作项目的时候,研究了mixins,此功能有妙处。用的时候有这样一个场景,页面的风格不一样,可是执行的方法,和须要的数据很是的类似。咱们是否要写两种组件呢?仍是保留一个而且而后另个一并兼容另外一个呢?vue

  • 无论以上那种方式都不是很合理,由于组件写成2个,不只麻烦并且维护麻烦;第二种虽然作了兼容可是页面逻辑形成混乱,必然不清晰;有没有好的方法,有那就是用vue的混合插件mixins。混合在Vue是为了提出类似的数据和功能,使代码易懂,简单、清晰。node

1.场景

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

//弹框
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个组件,或者一个兼容另外一个都不是合理方式。请看一下代码github

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文件,进行混合使用app

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的数据工具

三、能够全局混合(相似已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添加实例方法同样。this

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) {
    // 逻辑...
  }
}

有兴趣的能够试试,若想了解更多请关注github帐号holidayingprototype

相关文章
相关标签/搜索