Vue mixes into the same object, the merging rules of hooks

When a component and a mixin object contain options with the same name, these options will be "merged" in an appropriate way.

For example, data objects will be recursively merged internally, and component data will take precedence when conflicts occur.

const myMixin = {
  data() {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}

const app = Vue.createApp({
  mixins: [myMixin],
  data() {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created() {
    console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})

 

The hook functions of the same name will be merged into an array, so all will be called. In addition, the hook of the mixed object will be called before the hook of the component itself .

const myMixin = {
  created() {
    console.log('mixin hook called')
  }
}

const app = Vue.createApp({
  mixins: [myMixin],
  created() {
    console.log('component hook called')
  }
})

// => "混入对象的钩子被调用"
// => "组件钩子被调用"

 

Options whose values ​​are objects, such as  methods, components and  directives, will be combined into the same object. When the key names of two objects conflict, take the key-value pair of the component object.

const myMixin = {
  methods: {
    foo() {
      console.log('foo')
    },
    conflicting() {
      console.log('from mixin')
    }
  }
}

const app = Vue.createApp({
  mixins: [myMixin],
  methods: {
    bar() {
      console.log('bar')
    },
    conflicting() {
      console.log('from self')
    }
  }
})

const vm = app.mount('#mixins-basic')

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

Guess you like

Origin blog.csdn.net/lianjiuxiao/article/details/114024606
Recommended