• 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实例中进行局部使用。

  • 相关阅读:
    hdfs shell命令
    雪碧图
    绝对定位
    相对定位
    Vue 自定义指令
    Vue 【组件】组件注册、组件生命周期、动态组件、keep-alive
    Git 使用
    React 【生命周期】三个阶段生命周期函数、不同生命周期详解、图解生命周期
    【华为云技术分享】一统江湖大前端DOClever—你的Postman有点Low
    【华为云技术分享】圣诞特别版 | 数据库频频出现OOM问题该如何化解?
  • 原文地址:https://www.cnblogs.com/ashen1999/p/13700597.html
Copyright © 2020-2023  润新知