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

相關文章
相關標籤/搜索