Extending Vue

Extend with Mixins

Mixins are a flexible way to distribute reusable functionalities for Vue components. You can write a mixin just like a normal Vue component option object:

1
2
3
4
5
6
7
8
9
10
11
// mixin.js
module.exports = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
1
2
3
4
5
6
// test.js
var myMixin = require('./mixin')
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"

Extend with Plugins

Plugins usually adds global-level functionality to Vue.

Writing a Plugin

There are typically several types of plugins you can write:

  1. Add one or more global methods. e.g. vue-element
  2. Add one or more global assets: directives/filters/transitions etc. e.g. vue-touch
  3. Add some Vue instance methods by attaching them to Vue.prototype. The convention here is Vue instance methods should be prefixed with $, so that they don’t conflict with user data and methods.
1
2
3
4
5
exports.install = function (Vue, options) {
Vue.myGlobalMethod = ... // 1
Vue.directive('my-directive', {}) // 2
Vue.prototype.$myMethod = ... // 3
}

Using a Plugin

Assuming using a CommonJS build system:

1
2
3
var vueTouch = require('vue-touch')
// use the plugin globally
Vue.use(vueTouch)

You can also pass in additional options to the plugin:

1
2
3
Vue.use('my-plugin', {
/* pass in additional options */
})

Existing Tools