我的github iSAM2016
在練習寫UI組件的,用到全局的插件,網上看了些資料。看到些的挺好的,我也順便總結一下寫插件的流程;
聲明插件-> 寫插件-> 注冊插件 —> 使用插件
聲明插件
先寫文件,有基本的套路
Vue.js 的插件應當有一個公開方法 install 。
- 第一個參數是 Vue 構造器 ,
- 第二個參數是一個可選的選項對象:而options設置選項就是指,在調用這個插件時,可以傳一個對象供內部使用
// myPlugin.js
export default {
install: function (Vue, options) {
// 添加的內容寫在這個函數里面
}
};
注冊插件
import myPlugin from './myPlugin.js'
Vue.use(myPlugin)
寫插件
插件的范圍沒有限制——一般有下面幾種:
- 添加全局方法或者屬性
- 添加全局資源:指令/過濾器/過渡等
- 通過全局 mixin方法添加一些組件選項
- 添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現
- 一個庫,提供自己的 API,同時提供上面提到的一個或多個功能
// 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) {
// 邏輯...
}
添加全局方法或屬性
// code
Vue.test = function () {
alert("123")
}
// 調用
Vue.test()
**通過3.1添加,是在組件里,通過this.test()來調用**
**通過3.2添加,是在外面,通過Vue實例,如Vue.test()來調用**
添加全局資源
Vue.filter('formatTime', function (value) {
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小時
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
return new Date(value).Format("yyyy-MM-dd hh:mm:ss");
})
// 調用
{{num|formatTime}}
添加全局資源
Vue.mixin({
created: function () {
console.log("組件開始加載")
}
})
可以和【實例屬性】配合使用,用於調試或者控制某些功能
/ 注入組件
Vue.mixin({
created: function () {
if (this.NOTICE)
console.log("組件開始加載")
}
})
// 添加注入組件時,是否利用console.log來通知的判斷條件
Vue.prototype.NOTICE = false;
和組件中方法同名:
組件里若本身有test方法,並不會 先執行插件的test方法,再執行組件的test方法。而是只執行其中一個,並且優先執行組件本身的同名方法。這點需要注意
不需要手動調用,在執行對應的方法時會被自動調用的
添加實例方法或屬性
//讓輸出的數字翻倍,如果不是數字或者不能隱式轉換為數字,則輸出null
Vue.prototype.doubleNumber = function (val) {
if (typeof val === 'number') {
return val * 2;
} else if (!isNaN(Number(val))) {
return Number(val) * 2;
} else {
return null
}
}
//在組件中調用
this.doubleNumber(this.num);
