Svalidate.vue:
<template>
<div>
<slot :validate="validate"></slot>
{{errMsg}}
</div>
</template>
<script>
export default{
props:["value", "rules"],
data(){
return { errMsg: ""};
}
methods:{
validate(){
let validate = this.rules.reduce((pre, cur)=>{
let check = cur && cur.test && cur.test(this.value);
this.errMsg = check ? "" : cur.message;
return pre && check;
}, true);
return validate;
}
}
}
</script>
index.vue:
<template>
<s-validate #default="{validate}" :value="value" :rules="rules">
<input type="text" @blur="validate" v-model="value"/>
</s-validate>
<s-validate #default="{validate}" :value="text" :rules="textRules">
<textarea type="text" @blur="validate" v-model="text"/>
</s-validate>
</template>
<script>
import SValidate from "./SValidate";
export default{
data()=>{
value:"hi";
rules:[{
test:function(value){
return /\d+/.test(value);
},
message:"请输入一个数字"
}],
textRules:[{
test:function(value){
return value;
},
message:"请输入非空的值"
}]
}
components:{ SValidate }
}
</script>