May 07, 2021 Vue.js 2.0
Plug-ins typically add global functionality to Vue. There are no limits to the scope of plug-ins - there are generally the following:
Vue.js plug-ins should have an open method install. The first argument of this method is the Vue constructor, and the second argument is an optional option object:
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (options) {
// 逻辑...
}
}
Use the plug-in with the global method Vue.use():
// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
You can also pass in an option object:
Vue.use(MyPlugin, { someOption: true })
Vue.use automatically prevents the same plug-in from registering more than once, and only once.
Some plug-ins, such as vue-router, automatically call Vue.use() if Vue is a global variable. However, Vue.use() should always be explicitly called in a module environment:
// 通过 Browserify 或 Webpack 使用 CommonJS 兼容模块
var Vue = require('vue')
var VueRouter = require('vue-router')
// 不要忘了调用此方法
Vue.use(VueRouter)
awesome-vue brings together thousands of plug-ins and libraries from community contributions.