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>
<!-- 引入Vue库 -->
<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>
`
});
// 使用mixin
app.mixin({
// 实例创建完成后执行
created(){
// 遍历rules
for(let key in this.$options.rules){
// 取出当前规则
const item = this.$options.rules[key];
// 监控属性 key 发生变化,执行函数
this.$watch(key, value => {
// 执行每一条规则下的 validate 表达式
// value 是新的值
const result = item.validate(value);
// 如果返回 false 打印 规则里的 message
if(!result){
console.log(item.message);
}
});
}
}
});
const vm = app.mount('#root');
</script>
</html>
复制代码
运行结果
通过插件实现
<!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>
<!-- 引入Vue库 -->
<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>
`
});
// 定义一个插件:新写法,相当于写 install
const validatorPlugin = (app, options) => {
// 使用mixin
app.mixin({
// 实例创建完成后执行
created(){
// 遍历rules
for(let key in this.$options.rules){
// 取出当前规则
const item = this.$options.rules[key];
// 监控属性 key 发生变化,执行函数
this.$watch(key, value => {
// 执行每一条规则下的 validate 表达式
// value 是新的值
const result = item.validate(value);
// 如果返回 false 打印 规则里的 message
if(!result){
console.log(item.message);
}
});
}
}
});
}
// 使用插件
app.use(validatorPlugin);
const vm = app.mount('#root');
</script>
</html>
复制代码
运行结果
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END