Close
升级到 Vue 3 | Vue 2 EOL

插件

插件通常为 Vue 添加全局级别的功能。插件没有严格定义的范围 - 通常有几种类型的插件

  1. 添加一些全局方法或属性。例如 vue-custom-element

  2. 添加一个或多个全局资产:指令/过滤器/过渡等。例如 vue-touch

  3. 通过全局混入添加一些组件选项。例如 vue-router

  4. 通过将它们附加到 Vue.prototype 添加一些 Vue 实例方法。

  5. 一个提供自身 API 的库,同时注入上述组合。例如 vue-router

使用插件

通过调用 Vue.use() 全局方法来使用插件。这必须在你通过调用 new Vue() 启动应用程序之前完成。

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

new Vue({
//... options
})

你可以选择传入一些选项

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

Vue.use 会自动阻止你多次使用同一个插件,因此对同一个插件多次调用它只会安装一次插件。

Vue.js 官方插件提供的某些插件,例如 vue-router,如果 Vue 作为全局变量可用,则会自动调用 Vue.use()。但是,在 CommonJS 等模块环境中,你始终需要显式调用 Vue.use()

// 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)

查看 awesome-vue,了解大量社区贡献的插件和库。

编写插件

Vue.js 插件应该公开一个 install 方法。该方法将使用 Vue 构造函数作为第一个参数调用,以及可能的选项

MyPlugin.install = function (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = function () {
// some logic ...
}

// 2. add a global asset
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// some logic ...
}
...
})

// 3. inject some component options
Vue.mixin({
created: function () {
// some logic ...
}
...
})

// 4. add an instance method
Vue.prototype.$myMethod = function (methodOptions) {
// some logic ...
}
}