+1 vote
in VueJS by

What are the merging strategies in mixins?

1 Answer

0 votes
by

When a mixin and the component itself contain overlapping options, the options will be merged based on some strategies.

The data objects undergo a recursive merge, with the component’s data taking priority over mixins in cases of overlapping or conflicts.

var mixin = {

  data: function () {

    return {

      message: 'Hello, this is a Mixin'

    }

  }

 }

new Vue({

  mixins: [mixin],

  data: function () {

    return {

      message: 'Hello, this is a Component'

    }

  },

  created: function () {

    console.log(this.$data); // => { message: "Hello, this is a Component'" }

  }

})

The Hook functions which are overlapping merged into an array so that all of them will be called. Mixin hooks will be called before the component’s own hooks.

const myMixin = {

  created(){

    console.log("Called from Mixin")

  }

}

new Vue({

  el: '#root',

  mixins:[myMixin],

  created(){

    console.log("Called from Component")

  }

})

//Called from Mixin

//Called from Component

The options that expect object values(such as methods, components and directives) will be merged into the same object. In this case, the component’s options will take priority when there are conflicting keys in these objects.

var mixin = {

  methods: {

    firstName: function () {

      console.log('John')

    },

    contact: function () {

      console.log('+65 99898987')

    }

  }

}

var vm = new Vue({

  mixins: [mixin],

  methods: {

    lastName: function () {

      console.log('Murray')

    },

    contact: function () {

      console.log('+91 893839389')

    }

  }

})

vm.firstName() // "John"

vm.lastName() // "Murray"

vm.contact() // "+91 893839389"

What are custom options merging strategies?

Vue uses the default strategy which overwrites the existing value while custom options are merged. But if you want a custom option merged using custom login then you need to attach a function to Vue.config.optionMergeStrategies For the example, the structure of myOptions custom option would be as below,

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {

  // return mergedVal

}

Let's take below Vuex 1.0 merging strategy as an advanced example,

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)

  }

}

Related questions

0 votes
asked Jun 25, 2022 in Django by sharadyadav1986
+1 vote
asked Jan 27, 2020 in JavaScript by AdilsonLima
...