13). VueJS – Mixins
Basics
Mixins are a flexible way to reusable
functionalities for Vue components. A mixin object can contain any component
options. When a component uses a mixin, all options in the mixin will be
“mixed” into the component’s own options.
var mixin = { data: function () { return { message: 'hello', foo: 'abc' } } } new Vue({ mixins: [mixin], data: function () { return { message: 'goodbye', bar: 'def' } }, created: function () { console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" } } })
Option Merging
When a mixin and a
component contain overlapping options, they are merged as shown in the
following example.
Global Mixin
You can also apply a mixin globally. Use with caution! Once
you apply a mixin globally, it will affect every Vue instance created
afterwards. When used properly, this can be used to inject processing logic for
custom options:
Use global mixins carefully, because it affects every Vue instance created, including third party
components. In most cases, you should only use it for custom option handling
like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate
application.
Comments
Post a Comment