Vue项⽬elementUI中封装表单验证
1.直接在Vue⽂件中使⽤验证:
<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" @native="submitForm('ruleForm')"></el-input>                </el-form-item>
<div class="login-btn">
<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
</div>
<p >Tips : ⽤户名和密码随便填。</p>
</el-form>
</div>
</div>
</template>
<script>
export default {
data: function() {
let checkName = (rule, value, cb) => {
this.$storemit('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;
}
});
}
vue element admin
}
};
</script>
2. 使⽤vuex将需要⽤到的表单验证写在mutations.js⽂件中这需要安装vuex,步骤是:
cnpm i vuex --save
store/index.js
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
export const CHECK_NAME = 'checkName';
store/mutations.js
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
import store from './store/index';
Vue.prototype.$store = store;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。