plugin 案例 对数据做校验的插件
<!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></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="root"></div>
<script>
// plugin 对数据做校验的插件
var app = Vue.createApp({
data(){
return {
name: 'Eric',
age: 23
}
},
rules:{
age:{
validate: age => { return age > 25},
message: '太年轻了'
},
name:{
validate: name => { return name.length >=4},
message: 'name to 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')
</script>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号