Vue3 Mixins
Mixins define a part of reusable methods or computed properties. A mixin object can contain any component options. When a component uses the mixin object, all options of the mixin object will be mixed into the component's own options.
Let's look at a simple example:
Example
Try it Yourself »
Option Merging
When the component and the mixin object contain options with the same name, these options will be mixed in an appropriate way.
For example, data objects are shallowly merged internally (one level of property depth), and when conflicting with component data, the component data takes precedence.
In the following example, the Vue instance and the mixin object contain the same method. From the output result, we can see that the two options are merged.
Example
The output result is:
{"message":"goodbye","foo":"example","bar":"def"}
Try it Yourself »
Hook functions with the same name will be merged into an array, so all of them will be called. In addition, the hooks of the mixin object will be called before the component's own hooks.
const myMixin = {
created() {
console.log('mixin 对象的钩子被调用')
}
}
const app = Vue.createApp({
mixins: [myMixin],
created() {
console.log('组件钩子被调用')
}
})
// => "mixin 对象的钩子被调用"
// => "组件钩子被调用"Options whose values are objects, such as methods, components, and directives, will be merged into the same object. When two object key names conflict, the key-value pair of the component object is taken.
Example
In the above example, we called the following three methods:
vm.foo(); vm.bar(); vm.conflicting();
From the output result, in the methods option, if the same function name is encountered, the Vue instance has a higher priority and its output will be executed.
Global Mixin
You can also register a mixin object globally. Be careful when using it! Once a global mixin object is used, it will affect all Vue instances created afterwards. When used properly, it can inject processing logic for custom objects.
Example
Try it Yourself »
Use global mixin objects with caution, because they affect every individually created Vue instance (including third-party templates).
Other Extensions