6、数据校验插件
先使用app.mixin实现校验
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data(){
return{
name: 'zibo',
age: 25
}
},
rules: {
age: {
validate: age => age > 25,
message: "太年轻了!"
},
name: {
validate: name => name.length > 4,
message: "太短了!"
}
},
template: `
<div>name: {{name}} age: {{age}}</div>
`
});
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);
}
});
}
}
});
const vm = app.mount('#root');
</script>
</html>
运行结果
![image-20210614154734540.png](https://i-blog.csdnimg.cn/blog_migrate/46264a45a09871a6e7df9b94e05ba3d4.png)
通过插件实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data(){
return{
name: 'zibo',
age: 25
}
},
rules: {
age: {
validate: age => age > 25,
message: "太年轻了!"
},
name: {
validate: name => name.length > 4,
message: "太短了!"
}
},
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');
</script>
</html>
运行结果
![image-20210614160029084.png](https://i-blog.csdnimg.cn/blog_migrate/f2b6cf0f4558a122d00a62426296c95c.png)