Plugins

Writing a Plugin

Plugins usually add global-level functionality to Vue. There is no strictly defined scope for a plugin - there are typically several types of plugins you can write:

  1. Add some global methods or properties. 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.

  4. A library that provides an API of its own, while at the same time injecting some combination of the above. e.g. vue-router

A Vue.js plugin should expose an install method. The method will be called with the Vue constructor as the first argument, along with possible options:

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = ...
  // 2. add a global asset
  Vue.directive('my-directive', {})
  // 3. add an instance method
  Vue.prototype.$myMethod = ...
}

Using a Plugin

Use plugins by calling the Vue.use() global method:

// calls `MyPlugin.install(Vue)`
Vue.use(MyPlugin)

You can optionally pass in some options:

Vue.use(MyPlugin, { someOption: true })

Some plugins such as vue-router automatically calls Vue.use() if Vue is available as a global variable. However in a module environment you always need to call Vue.use() explicitly:

// When using CommonJS via Browserify or Webpack
var Vue = require('vue')
var VueRouter = require('vue-router')

// Don't forget to call this
Vue.use(VueRouter)

Existing Plugins & Tools

doc_VueJS
2016-09-25 05:48:12
Comments
Leave a Comment

Please login to continue.