vue中对输入框中的内容进行正则匹配

(1)首先进行HTML的编写,如下:

 1 <span>用户名:</span>
 2 <input type="text" v-model="usernameModel" placeholder="请输入用户名">
 3 <span>{{ userErrors.errorText }}</span>
 4 
 5 <span class="g-form-label">密码:</span>
 6 <input type="password" v-model="passwordModel" placeholder="请输入密码">
 7 <span class="g-form-error">{{ passwordErrors.errorText }}</span>
 8 
 9 <a class="button" @click="onLogin">登录</a>
10 
11 <p>{{ errorText }}</p>

(2)然后进行data的编写,如下:

1 data () {
2   return {
3     usernameModel: '',
4     passwordModel: '',
5     errorText: ''
6 }

(3)然后进行conputed属性的编写;即: 

computed:{
userErrors () { 2 let errorText, status 3 if (!/@/g.test(this.usernameModel)) { 4 status = false 5 errorText = '不包含@' 6 } 7 else { 8 status = true 9 errorText = '' 10 } 11 if (!this.userFlag) { 12 errorText = '' 13 this.userFlag = true 14 } 15 return { 16 status, 17 errorText 18 } 19 }, 20 passwordErrors () { 21 let errorText, status 22 if (!/^\w{1,6}$/g.test(this.passwordModel)) { 23 status = false 24 errorText = '密码不是1-6位' 25 } 26 else { 27 status = true 28 errorText = '' 29 } 30 if (!this.passwordFlag) { 31 errorText = '' 32 this.passwordFlag = true 33 } 34 return { 35 status, 36 errorText 37 } 38 } 39 }

(4)最后进行onLogin()方法的编写,即:

 1 methods: {
 2   onLogin () {
 3     if (!this.userErrors.status || !this.passwordErrors.status) {
 4       this.errorText = '部分选项未通过'
 5     }
 6     else {
 7       this.errorText = ''
 8       this.$http.get('api/login')
 9       .then((res) => {
10         this.$emit('has-log', res.data)
11       }, (error) => {
12         console.log(error)
13       })
14     }
15   }
16 }

猜你喜欢

转载自www.cnblogs.com/lanyb009/p/9231107.html