个人github iSAM2016
在练习写UI组件的,用到全局的插件,网上看了些资料。看到些的挺好的,我也顺便总结一下写插件的流程;
声明插件-> 写插件-> 注册插件 —> 使用插件vue
先写文件,有基本的套路
Vue.js 的插件应当有一个公开方法 install 。node
// myPlugin.js export default { install: function (Vue, options) { // 添加的内容写在这个函数里面 } };
import myPlugin from './myPlugin.js' Vue.use(myPlugin)
插件的范围没有限制——通常有下面几种:git
// 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方法。而是只执行其中一个,而且优先执行组件自己的同名方法。这点须要注意
不须要手动调用,在执行对应的方法时会被自动调用的github
//让输出的数字翻倍,若是不是数字或者不能隐式转换为数字,则输出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);
UI demo函数