组件核心代码代码,命名liang.js
/*
* @Liang liweiliang QQ:406320591(406320591@QQ.com).
* @date 2018-08-08,
* @version 1.0.0
* @liweiliang Inc. All Rights Reserved
*/
let Liang = {};
Liang.install = function(Vue,options){
Vue.prototype.$Validate = (_this) => {
var _Vaild = _this.dataset.vaild;
if(!!_Vaild){
var pattern = new RegExp(_Vaild);
if(pattern.test(_this.value)){
console.log("success");
}else{
var errmsg = _this.dataset.errmsg;
Vue.prototype.$toast({text:errmsg});
return false;
}
}else{
console.log("无验证规则");
}
return true;
};
Vue.prototype.$Vaild = (formElem) => {
var checkResult = true;
var elements = formElem.elements;
for (var i = 0; i < elements.length; i++) {
checkResult = Vue.prototype.$Validate(elements[i]) && checkResult;
if(!checkResult){
return false;
}
}
return checkResult;
}
}
export default Liang
使用方法在VUE中的main.js引入组件liang.js且全局方法使用
import Liang from "./utils/Liang"
Vue.use(Liang);
页面使用方法
给表单必须用form标签包起来,给form增加ref属性,
给对应的input增加对应的data-vaild正则验证属性,data-errmsg增加对应的错误提示信息内容
在提交的表单的按钮绑定请求方法,在请求前利用refs获取对应的表单然后利用封装好的this.Vaild进行数据校验
<div class="main_login">
<h4 class="main_login_title">欢迎登录</h4>
<form ref="login_form">
</form>
<input @click="handlerLogin" class="main_login_btn" type="button" value="登录">
<div class="main_login_Jump">
<router-link to="/register">快速注册</router-link>
<router-link to="/forgetpwd">忘记密码</router-link>
</div>
</div>
</template>
<script>
import axios from "axios"
export default {
name: 'login',
data (){
return{
phone:"",
password:"",
}
},
methods:{
handlerLogin() {
var formEle = this.$refs.login_form;
var isForm = this.$Vaild(formEle);
if(isForm){
var this_ = this;
axios.get('/static/json/test.json')
.then(function(response){
console.log(response);
this_.$store.commit("setToken","settokenlogin");
console.log(this_.$route.query.redirect)
this_.$router.push(this_.$route.query.redirect || '/')
})
.catch(function(err){
console.log(err);
});
}
}
}
}
</script>
<style scoped>
</style>