Vue mixin All In One


Vue mixin All In One

vue 2.x

  1. data 同名覆蓋, components 優先級高

var mixin = {
  data: function () {
    return {
      // ❌
      message: 'hello',
      foo: 'abc'
    }
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      // ✅
      message: 'goodbye',
      bar: 'def'
    }
  },
  created: function () {
    console.log(this.$data)
    // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})

  1. lifecycle hooks 同名共存,先執行 mixin, 后執行 components
var mixin = {
  created: function () {
    console.log('mixin hook called', 1);
  }
}

new Vue({
  mixins: [mixin],
  created: function () {
    console.log('component hook called', 2);
  }
})

// => "mixin hook called"
// => "component hook called"

  1. methods 同名覆蓋, components 優先級高
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"

Note that the same merge strategies are used in Vue.extend().

  1. Vue.mixin

global mixin

謹慎使用全局mixins,因為它會影響創建的每個Vue實例,包括第三方組件。

在大多數情況下,僅應將其用於自定義選項處理,如下例所示。


// inject a handler for `myOption` custom option
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
// => "hello!"

最好將它們作為插件發布以避免重復應用。

https://vuejs.org/v2/guide/plugins.html

demo

https://www.vuemastery.com/courses/next-level-vue/mixins/

合並自定義選項時,它們將使用默認策略來覆蓋現有值。

const merge = Vue.config.optionMergeStrategies.computed
Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
  if (!toVal) return fromVal
  if (!fromVal) return toVal
  return {
    getters: merge(toVal.getters, fromVal.getters),
    state: merge(toVal.state, fromVal.state),
    actions: merge(toVal.actions, fromVal.actions)
  }
}

https://github.com/vuejs/vuex

https://vuejs.org/v2/api/#optionMergeStrategies

vue 3.x


https://v3.vuejs.org/guide/mixins.html#custom-option-merge-strategies

Composition API

https://v3.vuejs.org/guide/composition-api-introduction.html


refs

https://vuejs.org/v2/guide/mixins.html

https://v3.vuejs.org/guide/mixins.html#mixins

Vue.mixin

https://vuejs.org/v2/api/#Vue-mixin

Vue.extend

https://vuejs.org/v2/api/#Vue-extend

https://vuejs.org/v2/api/#Vue-component





©xgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM