1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const app = Vue.createApp({ data() { return { name: 'dell', age: 23} }, rules: { age: { validate: age => age > 25, message: 'too young, to simple' }, name: { validate: name => name.length >= 4, message: 'name too short' } }, template: ` <div>name:{{name}}, age:{{age}}</div> ` }); const validatorPlugin = (app, options) => { app.mixin({ created() { 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); }) } } }) } app.use(validatorPlugin); const vm = app.mount('#root');
|