插件通常用來爲 Vue 添加全局功能。插件的功能範圍沒有嚴格的限制——一般有下面幾種:
1 添加全局方法或者 property。如:vue-custom-element
2 添加全局資源:指令/過濾器/過渡等。如 vue-touch
3 通過全局混入來添加一些組件選項。如 vue-router
4 添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現。
5 一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router
使用插件
————————————————————————————————————————————
通過全局方法 Vue.use()
使用插件。它需要在你調用 new Vue()
啓動應用之前完成:
// 調用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
new Vue({
// ...組件選項
})
也可以傳入一個可選的選項對象:
Vue.use(MyPlugin, { someOption: true })
開發插件
—————————————————————————————————————————————
Vue.js 的插件應該暴露一個 install 方法。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 邏輯...
}
...
})
// 3. 注入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
...
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}
DEMO – 指令
—————————————————————————————————————————————
插件JS文件:red.js,功能:使文字變紅。
let red = {}
red.install = function (Vue) {
Vue.directive('red', {
bind(el, binding) {
el.style.color = 'red';
}
})
}
export default red;
使用:
// 在main.js中引入並註冊插件
import red from 'red' //文件地址根據實際路徑而定
Vue.use(vueScrollwatch)
在組件中使用
<p v-red>hello world</p>
參考地址:Vue官方文檔-插件