Vue.config.optionMergeStrategies usage analysis

Vue.config.optionMergeStrategies is to define a merge strategy

In fact, it is the mixins attribute of vue. Receive an array [components], which is an instance of other vue.

Say you write this:

Vue.config.optionMergeStrategies.name = function (toVal, fromVal, vm) {
    return fromVal || toVal
}

Then when components are merged in, this rule will be followed. To put it bluntly, it is the merger of two objects

vm is the context of the current merged component

main.ts

import { createApp } from 'vue'
import App from './App.vue'

const myMixin = {
  custom: "mix custom",
  created() {
      console.log('mix')
  }
}

const app = createApp(App)

app.config.optionMergeStrategies.custom = (toVal, fromVal, vm) => {
  console.log(toVal, fromVal)
  console.log(vm)
  return fromVal || toVal
}

app.mixin(myMixin)

app.mount('#app')

Component App.vue


<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App',
  custom: "app custom",
  created() {
    console.log(this.$options.custom)
  }
})
</script>

We will find that created will not be overwritten. Vue combines hook functions into an Array<hook>, so each created will be called. 

All the options of Vue have their own merging strategies, interested students can read its source code!

 

Guess you like

Origin blog.csdn.net/weixin_42335036/article/details/90266467