Vue.js Mixins
Mixins define a set of reusable methods or computed properties. A mixin object can contain any component options. When a component uses a mixin object, all of the mixin object's options are merged into the component's own options.
Here is a simple example:
Example
var
vm
=
new
Vue
(
{
el
:
'
#databinding
'
,
data
:
{
}
,
methods
:
{
}
,
}
)
;
//
Define a mixin object
var
myMixin
=
{
created
:
function
(
)
{
this
.
startmixin
(
)
}
,
methods
:
{
startmixin
:
function
(
)
{
document
.
write
(
"
Welcome to the mixin example
"
)
;
}
}
}
;
var
Component
=
Vue
.
extend
(
{
mixins
:
[
myMixin
]
}
)
var
component
=
new
Component
(
)
;
Try it »
Option Merging
When a component and a mixin object contain options with the same name, these options are merged in an appropriate way.
For example, data objects are shallow-merged internally (one level of property depth), and when conflicting with the component's data, the component data takes precedence.
In the example below, the Vue instance and the mixin object contain the same methods. From the output, you can see that the two options are merged.
Example
var
mixin
=
{
created
:
function
(
)
{
document
.
write
(
'
Mixin call
'
'
'
)
}
}
new
Vue
(
{
mixins
:
[
mixin
]
,
created
:
function
(
)
{
document
.
write
(
'
Component call
'
'
'
)
}
}
)
;
The output is:
混入调用
组件调用
Try it »
If the methods option has a function with the same name, the Vue instance takes higher priority. In the following example, both the Vue instance and the mixin object's methods option contain the same function:
Example
var
mixin
=
{
methods
:
{
hellworld
:
function
(
)
{
document
.
write
(
'
HelloWorld method
'
'
'
)
;
}
,
samemethod
:
function
(
)
{
document
.
write
(
'
Mixin: same method name
'
'
'
)
;
}
}
}
;
var
vm
=
new
Vue
(
{
mixins
:
[
mixin
]
,
methods
:
{
start
:
function
(
)
{
document
.
write
(
'
start method
'
'
'
)
;
}
,
samemethod
:
function
(
)
{
document
.
write
(
'
Main: same method name
'
'
'
)
;
}
}
}
)
;
vm
.
hellworld
(
)
;
vm
.
start
(
)
;
vm
.
samemethod
(
)
;
The output is:
HelloWorld 方法
start 方法
Main:相同方法名
Try it »
In the example above, we called the following three methods:
vm.hellworld();
vm.start();
vm.samemethod();
From the output, if the methods option encounters the same function name, the Vue instance has higher priority and its output is executed.
Global Mixin
You can also register mixin objects globally. Use with caution! Once a global mixin object is used, it will affect ALL Vue instances created afterward. Used appropriately, it can inject processing logic into custom objects.
Example
//
Inject a handler for the custom option 'myOption'.
Vue
.
mixin
(
{
created
:
function
(
)
{
var
myOption
=
this
.$
options
.
myOption
if
(
myOption
)
{
console
.
log
(
myOption
)
}
}
}
)
new
Vue
(
{
myOption
:
'
hello!
'
}
)
//
=> "hello!"
Try it »
Use global mixin objects with caution, as they affect every individually created Vue instance (including third-party templates).