vue 开发插件流程

UI demo
UI 插件汇总

我的github iSAM2016
在练习写UI组件的,用到全局的插件,网上看了些资料。看到些的挺好的,我也顺便总结一下写插件的流程;
声明插件-> 写插件-> 注册插件 —> 使用插件

声明插件

先写文件,有基本的套路
Vue.js 的插件应当有一个公开方法 install 。

  1. 第一个参数是 Vue 构造器 ,
  2. 第二个参数是一个可选的选项对象:而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);

UI demo

posted @ 2017-03-07 14:24  急眼的蜗牛  阅读(2235)  评论(2编辑  收藏  举报