VUE--封装插件

插件的核心是install函数,第一个参数是Vue对象,第二个参数是options配置参数。当通过vue.use()调用插件时,即执行install方法

通过mixins创建全局插件

以下封装了一个数据验证的插件rules。通过在vue实例的$options中添加rules,实现对实例中data的监听

const validatePlugin = {
   // 使用vue.use调用时执行
  install: function (vue) {
   // 向全局mixin对象中添加
    vue.mixin({
   // 在created生命周期函数中
      created() {
   // 判断options中是否存在rules属性
        if (this.$options.hasOwnProperty(rules)) {
   // 拿到rules中的每一条规则(key,对应data中的数据),遍历
          Object.keys(this.$options.rule).forEach((key) => {
            const rule = this.$options.rules[key];
            // 监听数据改变,进行验证
            this.$watch(key, (newVal) => {
              const result = rule.validate(newVal);
              if(!result){
                console.log(rule.message)
              }
            });
          });
        }
      },
    });
  },
};

Vue.use(validatePlugin);

使用方法如下:

每当该实例中的foo属性改变,就会触发这个验证机制。当foo小于等于1时,就会在控制台输出message

const vm = new Vue({
  data: { foo: 10 },
  rules: {
    foo: {
      validate: (value) => value > 1,
      message: "foo must be greater than one",
    },
  },
});

封装控件

先与创建其他vue实例相同,构建控件需要实现的效果

再在js文件中,实现install方法,并暴露为全局对象

以下为封装消息弹框控件toast的示例,假定toast.vue实现了效果。在toast.js文件中:

import toast from './toast.vue'
var toastObj = {}
toastObj.install = function(vue){
    const toastConstructor = vue.extend(toast)
    const toast = new toastConstructor()
    toast.$mount(document.creatElement('div'))
    document.body.appendChild(toast.$el)
    vue.prototype.toast = toast
}

之后,可以在main.js文件中,通过vue.use(toast)全局使用toast控件;

也可以在任何vue实例中进行局部使用。

posted @ 2020-09-20 15:31  ashen1999  阅读(115)  评论(0编辑  收藏  举报