您的位置:首页 > Web前端 > Vue.js

Vue项目elementUI中封装表单验证

2018-07-20 10:27 726 查看

1.直接在Vue文件中使用验证:

[code]<template>
<div class="login-wrap">
<div class="ms-title">后台管理系统</div>
<div class="ms-login">
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
<el-form-item prop="username">
<el-input v-model="ruleForm.username" placeholder="username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" placeholder="password" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
</el-form-item>
<div class="login-btn">
<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
</div>
<p style="font-size:12px;line-height:30px;color:#999;">Tips : 用户名和密码随便填。</p>
</el-form>
</div>
</div>
</template>

<script>
export default {
data: function() {
let checkName = (rule, value, cb) => {
this.$store.commit('checkName',{rule,value,cb});
};
return {
ruleForm: {
username: "admin",
password: "123123"
},
rules: {
username: [
{ required: true, message: "请输入用户名", trigger: "blur" },
{ validator: checkName }
// { min:10 , message:'最少10个字符',trigger:'blur'},
// { pattern: /^[\u4E00-\u9FA5]+$/, message:'用户名只能是中文'},
// { pattern:/^[a-zA-Z]w{5,17}$/, message: '以字母开头,长度在6-18之间, 只能包含字符、数字和下划线'}
],
password: [{ required: true, message: "请输入密码", trigger: "blur" }]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
localStorage.setItem("ms_username", this.ruleForm.username);
this.$router.push("/");
} else {
console.log("error submit!!");
return false;
}
});
}
}
};
</script>

2. 使用vuex将需要用到的表单验证写在mutations.js文件中

这需要安装vuex,步骤是:

  • cnpm i vuex --save
  • store/index.js
    [code]import Vue from 'vue';
    import Vuex from 'vuex';
    import state from './state';
    import mutations from './mutations';
    import actions from './actions';
    Vue.use(Vuex);
    const store = new Vuex.Store({
    state,
    mutations,
    actions
    });
    export default store;

     

  • store/mutations_type.js
[code]export const CHECK_NAME = 'checkName';
  • store/mutations.js
[code]import {
CHECK_NAME
} from './mutations_type';
export default {
[CHECK_NAME](state , obj){
if(!obj.value){
obj.cb(new Error('请输入用户名'));
}else if(!/^[\u4E00-\u9FA5]+$/.test(obj.value)){
obj.cb(new Error('用户名只能是中文'));
}else{
obj.cb();
}
}
}
  •  将vuex引入main.js 
  • [code]import store from './store/index';
    Vue.prototype.$store = store;

     

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: