0
点赞
收藏
分享

微信扫一扫

Vue3 | Mixin、自定义指令、Teleport传送门、Render函数、插件 详解 及 案例分析

码农K 2021-09-19 阅读 81



本文内容提要


Mixin基础

如果组件本身有 自身定义的data字段 且与 引入的Mixin 模块data字段有冲突,
则以组件本身的字段为准;

例程1:
组件本身定义number一个字段,
Mixin定义了numbercount两个字段,
组件引入Mixin后,使用数据时,number以组件为准,count则可以直接使用Mixin的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const myMixin = {
        data() {
            return {
                number: 666,
                count: 666
            }
        }
    }

    const app = Vue.createApp({
        data() {
            return {
                number: 1
            }
        },
        mixins: [myMixin],
        template: `
            <div>
                <div>{{number}}</div>
                <div>{{count}}</div>
            </div>`
    });

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


Mixin 之 methods

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const myMixin = {
        created() {
            console.log('mixin created');
        },
        methods: {
            handleClick() {
                console.log("mixin methods");
            }
        }
    }

    const myMixin2 = {
        created() {
            console.log('mixin2 created');
        },
        methods: {
            handleClick() {
                console.log("mixin2 methods");
            }
        }
    }

    const app = Vue.createApp({
        data() {
            return {
                number: 1
            }
        },
        created() {
            console.log('rootApp created');
        },
        mixins: [myMixin, myMixin2],
        methods: {
            handleClick() {
                console.log("rootApp methods");
            }
        },
        template: `
            <div>
                <div>{{number}}</div>
                <button @click="handleClick">testButton</button>
                </div>`
    });

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:

如下,自定义新的规则为——如果存在mixinValue,
默认优先返回mixinValue,不存在再返回appValue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const myMixin = {
        myNumber: 1
    }

    const app = Vue.createApp({
        mixins: [myMixin],
        myNumber: 666,
        template: `
            <div>
                <div>{{this.$options.myNumber}}</div>
            </div>`
    });

    app.config.optionMergeStrategies.myNumber = (mixinValue, appValue) => {
        return mixinValue || appValue;
    }
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


Mixin 之 生命周期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const myMixin = {
        created() {
            console.log('mixin created');
        }
    }

    const myMixin2 = {
        created() {
            console.log('mixin2 created');
        }
    }

    const app = Vue.createApp({
        data() {
            return {
                number: 1
            }
        },
        created() {
            console.log('rootApp created');
        },
        mixins: [myMixin, myMixin2],
        template: `
            <div>
                <div>{{number}}</div>
            </div>`
    });

    const vm = app.mount('#heheApp');
</script>
</html>


本例此前的Mixin都是局部Mixin!!在父组件中引入的Mixin,无法在子组件中使用

如下,父组件引入的Mixin【myMixin】,无法在子组件【child】中使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const myMixin = {
        data() {
            return {
                count: 666
            }
        },
        created() {
            console.log('mixin created');
        },
        methods: {
            handleClick() {
                console.log("mixin methods");
            }
        }
    }

    const app = Vue.createApp({
        data() {
            return {
                number: 1
            }
        },
        created() {
            console.log('rootApp created');
        },
        mixins: [myMixin],
        methods: {
            handleClick() {
                console.log("rootApp methods");
            }
        },
        template: `
            <div>
                <div>{{number}}</div>
                <child />
                <button @click="handleClick">testButton</button>
                </div>`
    });

    app.component('child', {
        template:`<div>{{count}}</div>`
    })

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


自定义指令 directive

使用自定义指令封装focus逻辑,优化上例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        template: `
            <div>
                <input v-focus>
            </div>`
    });

    app.directive('focus', {
        mounted(el) {
            el.focus();
        }
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果,自动聚焦:


以上是全局定义的自定义指令,下面是 局部自定义指令

同样实现上例效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const myDirective = {
        focus: {
            mounted(el) {
                el.focus();
            }
        }
    }

    const app = Vue.createApp({
        directives: myDirective,
        template: `
            <div>
                <input v-focus>
            </div>`
    });
    
    const vm = app.mount('#heheApp');
</script>
</html>

-再例:再验生命周期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                hehe: true
            }
        },
        template: `
            <div>
                <div v-show="hehe">
                    <input v-focus>
                </div>    
            </div>`
    });

    app.directive('focus', {
        beforeMount() {
            console.log('beforeMount');
        },
        mounted(el) {
            console.log('mounted');
            el.focus();
        },
        beforeUpdate() {
            console.log('beforeUpdate');
        },
        updated() {
            console.log('updated');
        }
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:

再例2:

根据v-show和v-if的特性不同,会触发的生命周期钩子 也不一样:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                hehe: true
            }
        },
        template: `
            <div>
                <div v-if="hehe">
                    <input v-focus>
                </div>    
            </div>`
    });

    app.directive('focus', {
        beforeMount() {
            console.log('beforeMount');
        },
        mounted(el) {
            console.log('mounted');
            el.focus();
        },
        beforeUpdate() {
            console.log('beforeUpdate');
        },
        updated() {
            console.log('updated');
        },
        beforeUnmount() {
            console.log('beforeUnmount');
        },
        unmounted() {
            console.log('unmounted');
        },
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


自定义指令 结合 style 【自定义指令传参】

自定义指令 中的钩子,
除了默认第一个参数【el】 为修饰的DOM节点外,
还可以有第二个参数【binding】,
这个参数可以把 使用 本自定义指令时,传过来的参数 都 囊括其中;

如下,
定义css类【header】,指定为绝对布局样式;
自定义指令pos
钩子接收两个参数——el、binding
使用指令时,传入一个数值参数【80】,
这在指令中,会被接收,然后用于定义style布局样式——
el.style.top = (binding.value + 'px');

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .header {position: absolute}
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                hehe: true
            }
        },
        template: `
            <div>
                <div v-pos="80" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', {
        mounted(el, binding) {
            el.style.top = (binding.value + 'px');
        }
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


换成180:

...
template: `
            <div>
                <div v-pos="180" class="header">
                    <input />
                </div>    
            </div>`
...

运行效果:



再结合data 和 updated钩子,将上例 动态化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .header {position: absolute}
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                topMargin: 66
            }
        },
        template: `
            <div>
                <div v-pos="topMargin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', {
        mounted(el, binding) {
            el.style.top = (binding.value + 'px');
        },
        updated(el, binding) {
            el.style.top = (binding.value + 'px');
        }
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:

初始:

动态赋值:

效果:


简化上例 的 设计技巧

例程:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .header {position: absolute}
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                topMargin: 66
            }
        },
        template: `
            <div>
                <div v-pos="topMargin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', (el, binding) => {
        el.style.top = (binding.value + 'px');
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

即当自定义指令里边,
只有mountedupdated两个钩子 且 这两个钩子的内容参数列表 是 完全一样的话,
我们可以简写成下面的写法,
即变对象为函数,函数的内容 为 钩子中相同的内容:

    app.directive('pos', (el, binding) => {
        el.style.top = (binding.value + 'px');
    })

这种写法 是 等价于上例的写法的:

      app.directive('pos', {
        mounted(el, binding) {
            el.style.top = (binding.value + 'px');
        },
        updated(el, binding) {
            el.style.top = (binding.value + 'px');
        }
    })


打印binding对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .header {position: absolute}
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
                topMargin: 66
            }
        },
        template: `
            <div>
                <div v-pos:heheda="topMargin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', (el, binding) => {
        console.log(binding, 'binding');
        el.style.top = (binding.value + 'px');
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


用上binding.arg,自定义更加灵活

直接v-pos:top="topMargin"
[自定义指令]:[arg]="[value]"的结构;
如下例的写法,用户 既可以配置style的值,也可以 配置style的属性:

如下,
配置为top的margin,数值是80:

<script>

    const app = Vue.createApp({
        data() {
            return {
                margin: 80
            }
        },
        template: `
            <div>
                <div v-pos:top="margin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', (el, binding) => {
        el.style[binding.arg] = (binding.value + 'px');
    })
    
    const vm = app.mount('#heheApp');
</script>

运行效果:


配置为right的margin,数值是80:

<script>

    const app = Vue.createApp({
        data() {
            return {
                margin: 80
            }
        },
        template: `
            <div>
                <div v-pos:right="margin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', (el, binding) => {
        el.style[binding.arg] = (binding.value + 'px');
    })
    
    const vm = app.mount('#heheApp');
</script>

运行效果:

配置为left的margin,数值是80:

<script>

    const app = Vue.createApp({
        data() {
            return {
                margin: 80
            }
        },
        template: `
            <div>
                <div v-pos:left="margin" class="header">
                    <input />
                </div>    
            </div>`
    });

    app.directive('pos', (el, binding) => {
        el.style[binding.arg] = (binding.value + 'px');
    })
    
    const vm = app.mount('#heheApp');
</script>

运行效果:


CSS基础案例回顾——居中布局

首先,
left: 50%;top: 50%;
使得使用该CSS类的 DOM节点 的 左上角顶点,
在窗口的中点处:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .area {
            position: absolute;
            left: 50%;
            top: 50%;
            width: 228px;
            height: 336px;
            background: paleturquoise;}
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return {
            }
        },
        template: `
            <div class="area">  
            </div>`
    });
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:

再加上一笔,
transform: translate(-50%, -50%);使得组件在上面两个margin之后,
让本节点移动(-50%, -50%)的距离,
其实就是 左移和上移 分别为 节点宽高的一半 的距离:

<style>
        .area {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 228px;
            height: 336px;
            background: paleturquoise;}
</style>

运行效果:


局部蒙版

如下添加.mask这个蒙版样式,
绝对布局,左上右下四方为0,即遍布父布局(<div class="area">):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <style>
        .area {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 228px;
            height: 336px;
            background: paleturquoise;}
        .mask {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background: #000;
            opacity: 0.5;
        }
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const app = Vue.createApp({
        data() {
            return {
                show: false
            }
        },
        methods: {
            handleBtnClick() {
                this.show = !this.show;
            }
        },
        template: `
            <div class="area">  
                <button @click="handleBtnClick">蒙版</button>
                <div class="mask" v-show="show"></div>
            </div>`
    });
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行,点击按钮,显示蒙版:


Teleport传送门 助力 全局蒙版

欲将上例中的【局部蒙版】升级成【全局蒙版】,
需要调用DOM将<div class="mask" v-show="show"></div>送到<body>的第一子组件位置,
这样 蒙版节点css样式的 遍布父布局的 特性,
就可以直接遍布 整个body 成为【全局蒙版】了,
这个时候就可以使用【Teleport】进行助力了:


使用<teleport>标签将其包裹起来,指定to="body"传送到 body:

... 
  template: `
            <div class="area">  
                <button @click="handleBtnClick">蒙版</button>
                <teleport to="body">
                    <div class="mask" v-show="show"></div>
                </teleport>    
            </div>`
...

运行效果:

或者传送到某个body下覆盖全局的DOM节点上,

...
<body>
    <div id="heheApp"></div>
    <div id="heheda"></div>
</body>
<script>
    const app = Vue.createApp({
       ...
        template: `
            <div class="area">  
                <button @click="handleBtnClick">蒙版</button>
                <teleport to="#heheda">
                    <div class="mask" v-show="show"></div>
                </teleport>    
            </div>`
    });
    ...
</script>
</html>

运行效果同上例,
结构图:


Render函数

首先假设有这么一个需求,
定义一个子组件,
接受调用它的父组件的一个参数level
子组件 根据这个level显示不同的DOM节点

最基本的也许我们会写成这样:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const app = Vue.createApp({
        template: `
            <my-title :level="2">
                heheda
            </my-title>    
        `
    });

    app.component('my-title', {
        props: ['level'],

        template:
        `
            <h1 v-if="level === 1"><slot /></h1>
            <h2 v-if="level === 2"><slot /></h2>
            <h3 v-if="level === 3"><slot /></h3>
            <h4 v-if="level === 4"><slot /></h4>`
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


使用Render函数优化
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>
    const app = Vue.createApp({
        template: `
            <my-title :level="6">
                heheda
            </my-title>    
        `
    });

    app.component('my-title', {
        props: ['level'],

        render() {
            const { h } = Vue;
            return h('h' + this.level, {}, this.$slots.default());
        }
    })
    
    const vm = app.mount('#heheApp');
</script>
</html>

关键代码:

        render() {
            const { h } = Vue;
            return h('h' + this.level, {}, this.$slots.default());
        }

运行效果:

传参level改成3:

使用Render函数 生成多层嵌套UI
<script>
    const app = Vue.createApp({
        template: `
            <my-title :level="1">
                heheda
            </my-title>    
        `
    });

    app.component('my-title', {
        props: ['level'],

        render() {
            const { h } = Vue;
            return h('h' + this.level, {}, [
                this.$slots.default(),
                h('h' + String(Number(this.level) + 1), {}, [
                    this.$slots.default(),
                    h('h' + String(Number(this.level) + 3), {},
                        this.$slots.default()
                    )
                ])
            ]);
        }
    })
    
    const vm = app.mount('#heheApp');
</script>

运行效果:


插件 —— 使用provide提供数据给 子组件 使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const myPlugin = {
        install(app, options) {
            app.provide('myTestKey', "lululu");
        }
    }

    const app = Vue.createApp({
        template: `
            <my-title />    
        `
    });

    app.component('my-title', {
        inject: ['myTestKey'],
        template: `<div>{{myTestKey}}</div>`
    })

    app.use(myPlugin, {})
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


插件 —— 自定义指令 供 (子)组件使用

...
<script>

    const myPlugin = {
        install(app, options) {
            app.directive('focus', {
                mounted(el) {
                    el.focus();
                }
            })
        }
    }

    const app = Vue.createApp({
        template: `
            <my-title />    
        `
    });

    app.component('my-title', {
        template: `
        <div><input /></div>
        <div><input v-focus /></div>
        <div><input /></div>`
    })

    app.use(myPlugin, {})
    const vm = app.mount('#heheApp');
</script>
...

运行效果:


插件 —— 拓展生命周期

<script>

    const myPlugin = {
        install(app, options) {
            app.mixin({
                mounted() {
                    console.log('mixin');
                }
            })
        }
    }

    const app = Vue.createApp({
        template: `
            <my-title />    
        `
    });

    app.component('my-title', {
        template: `
        <div><input /></div>`
    })

    app.use(myPlugin, {})
    const vm = app.mount('#heheApp');
</script>

运行效果:


插件 —— 拓展底层变量

<script>

    const myPlugin = {
        install(app, options) {
            app.config.globalProperties.$heheDa = "heheda!";
        }
    }

    const app = Vue.createApp({
        template: `
            <my-title />    
        `
    });

    app.component('my-title', {
        mounted() {
            console.log(this.$heheDa);
        },
        template: `
        <div><input /></div>`
    })

    app.use(myPlugin, {})
    const vm = app.mount('#heheApp');
</script>

运行效果:


Mixin方案 —— 对数据做校验 案例

首先打印观察rules对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return { myName: 'zhao', age: 66}
        },
        rules: {
            age: {
                // validate: age => {return age > 23},
                validate: age => age > 23,
                message: 'too young, to simple'
            },
            myName: {
                validate: myName => myName !== 'zhao',
                message: 'heheda'
            }
        },
        template: `
            <div>name:{{myName}}, age:{{age}} </div>    
        `
    });

    app.mixin({
        created() {
            console.log(this.$options.rules);
            for(let key in this.$options.rules) {
                const item = this.$options.rules[key];
                console.log(key, item);
            }
        }
    })

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


每层迭代 增加监听

例程:
遍历rules的key,
每一层迭代里——
对每一个key,都用这个key去获取对应的rule对象,赋给item,
然后对item的key【被校验字段】设置监听

key/被校验字段发生改变时,触发回调,
这时,可以用[rule对象].validate()去校验值,然后返回结果,
如果校验不通过,
可以用[rule对象].message获取到我们准备好的话术!!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return { myName: 'zhao', age: 66}
        },
        rules: {
            age: {
                // validate: age => {return age > 23},
                validate: age => age > 23,
                message: 'too young, to simple'
            },
            myName: {
                validate: myName => myName.length > 3,
                message: 'heheda'
            }
        },
        template: `
            <div>name:{{myName}}, age:{{age}} </div>    
        `
    });

    app.mixin({
        created() {
            console.log(this.$options.rules);
            for(let key in this.$options.rules) {
                const item = this.$options.rules[key];
                this.$watch(key, (value) => {
                    const result = item.validate(value);
                    if(!result) console.log(item.message);
                })
                console.log(key, item);
            }
        }
    })

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


将 校验mixin 封装进 plugin

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({
        data() {
            return { myName: 'zhao', age: 66}
        },
        rules: {
            age: {
                // validate: age => {return age > 23},
                validate: age => age > 23,
                message: 'too young, to simple'
            },
            myName: {
                validate: myName => myName.length > 3,
                message: 'heheda'
            }
        },
        template: `
            <div>name:{{myName}}, age:{{age}} </div>    
        `
    });

    const validatorPlugin = (app, options) => {
        app.mixin({
            created() {
                console.log(this.$options.rules);
                for(let key in this.$options.rules) {
                    const item = this.$options.rules[key];
                    this.$watch(key, (value) => {
                        const result = item.validate(value);
                        if(!result) console.log(item.message);
                    })
                    console.log(key, item);
                }
            }
        })
    };

    app.use(validatorPlugin);
    const vm = app.mount('#heheApp');
</script>
</html>

运行效果同上例;

举报

相关推荐

0 条评论