vue插件

vue插件

我们日常使用插件的方式是: Vue.use(plugin),但是插件是如何写出来的?

关键概念: install -> mixin -> $options.rules -> $watch

  1. install

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // vue 中的插件固定写法
    const RulesPlugin = {
    // Implement this!
    install(Vue) {
    Vue.mixins({
    created() {
    if (this.$options.rules) {
    // do some thing


    })
    }
    }
    })
    }
    }

    Vue.use(RulesPlugin)

    解释一下, vue中插件都会提供一个install , 本质上是往vue上挂载相应的函数,函数内部是用全局的mixin来往根实例添加功能

  2. mixin

    mixin, 一种代码复用的语法糖, 插件的挂载都是用全局mixin来完成的.

  3. $options.rules

    该对象中承载了我们的在组件实例中的自定义插件, 在本例中就是实例中的rules。

  4. $watch

    watch的js语法, 两个参数, 1 观测的属性名 2 .回调函数

完整实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const RulesPlugin = {
// Implement this!
install(Vue) {
Vue.mixins({
created() {
if (this.$options.rules) {
// solution
Object.keys(this.$options.rules).map(key => {
const rule = this.$options.rules[key]
this.$watch(key, (newValue) => {
const result = rule.validate(newValue)
if(!result) {
console.log(rule.message)
}
})
})
}
}
})
}
}

Vue.use(RulesPlugin)