深入Vue-Plugin


Plugin

2.1 Simple Plugin

Goal

Create a plugin that teaches Vue components to handle a custom “rules”
option. The “rules” option expects an object that specifies validation rules
for data in the component.

Expected usage:

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

vm.foo = 0 // should log: "foo must be greater than one"

Hints

  1. The plugin should install a global mixin
  2. The global mixin contains a “created” hook
  3. In the hook, check for this.$options.rules

实现

    const RulesPlugin = {
      install (Vue) {
        Vue.mixin({
          created () {
            if (this.$options.hasOwnProperty('rules')) {
              // Do something with rules
              const rules = this.$options.rules
              Object.keys(rules).forEach(key => {
                const rule = rules[key]
                this.$watch(key, newValue => {
                  const result = rule.validate(newValue)
                  if (!result) {
                    console.log(rule.message)
                  }
                })
              })
            }
          }
        })
      }
    }

    Vue.use(RulesPlugin)

文章作者: 沐雪
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 沐雪 !
评论
 上一篇
深入Vue-RenderFunction 深入Vue-RenderFunction
Render Function3.1 Dynamically Render Tagstemplate =>编译成Render Function => 返回一个新的虚拟DOM => 生成真实的DOM 真实DOM docu
2019-04-10 沐雪
下一篇 
深入Vue-Reactivity 深入Vue-Reactivity
Reactivity1.1 Getters and Setters目标实现一个 convert 函数: 接收一个 Object 作为参数 使用 object.defineProperty 将对象的属性就地转换为 getter/sette
2019-04-09 沐雪
  目录