/*
<div id="root">
<div class="left">
<p><span>账号:</span><input type="text" @blur='isName(uname)' v-model="uname" placeholder="输入账户,2~5长度"></p>
<p><span>密码:</span><input type="text" @blur='isPwd(pwd)' v-model="pwd" placeholder="密码是字母和数字组合"></p>
<p><span>性别:</span>
<input type="radio" name='sex' value='男' v-model='gender'>男
<input type="radio" name='sex' value='女' v-model='gender'>女
</p>
<p><span>年龄:</span><input type="text" @blur='isAge(age)' v-model='age'></p>
<button @click='addInfo'>添加用户</button>
</div>
<div class="right">
<table>
<thead>
<tr>
<center>用户信息列表</center>
<td><input type="checkbox" v-model='all' @change='checkAll(all)'>全选</td>
<td>账号</td>
<td>密码</td>
<td>性别</td>
<td>年龄</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for='(item,index) in info' :key='index' v-if='info.length!=0'>
<td><input type="checkbox" v-model='item.done' @change='checkOne(item.done)'></td>
<td>{{item.uname}}</td>
<td>{{item.pwd}}</td>
<td>{{item.gender}}</td>
<td>{{item.age}}</td>
<td><button @click='del(index)'>删除</button></td>
</tr>
<tr v-if='info.length==0'>
<td colspan="6" style="width: 600px;">还没有用户信息哟,快去添加吧</td>
</tr>
</tbody>
</table>
<button v-if='show' @click='delDone'>删除已勾选</button>
</div>
</div>
*/
// 创建vue实例
const vm = new Vue({
// 指定容器
el: '#root',
data: {
info: JSON.parse(localStorage.getItem('info')) || [],
all: false,
uname: '',
pwd: '',
gender: '男',
age: '',
done: false,
show: false,
},
methods: {
// 验证账号
isName(uname) {
if (!/^[0-9A-Za-z]{2,5}$/.test(uname) || uname === 'admin') {
alert('账户长度应在2-5之间,且不能取名为admin')
this.uname = ''
return
}
},
// 验证密码
isPwd(pwd) {
const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{2,}$/
if (!reg.test(pwd)) {
alert('密码必须是字母和数字的组合')
this.pwd = ''
return
}
},
// 验证年龄
isAge(age) {
if (!/^\d+$/.test(age)) {
alert('年龄必须是数字')
this.age = ''
return
} else if (+age <= 0 || +age > 200) {
alert('年龄必须在1~200之间')
this.age = ''
return
}
},
// 添加用户
addInfo() {
if (!this.uname || !this.pwd || !this.gender || !this.age) {
console.log(!this.uname);
alert('所有信息都不能为空')
this.uname = this.pwd = this.checked = this.age = ''
return
} else {
// 放到info数组,存本地
this.info.unshift({
uname: this.uname,
pwd: this.pwd,
gender: this.gender,
age: this.age,
done: this.done,
})
console.log(this.info)
localStorage.setItem('info', JSON.stringify(this.info))
this.uname = this.pwd = this.checked = this.age = ''
}
},
// 删除用户
del(i) {
if (confirm('确定要删除嘛?')) {
this.info.splice(i, 1)
localStorage.setItem('info', JSON.stringify(this.info))
}
},
// 全选
checkAll(all) {
this.info.forEach(item => item.done = all)
this.show = all
},
// 勾选 取消勾选
checkOne(done) {
// 循环数组判断选中了几个
let i = 0
this.info.forEach(item => {
if (item.done === true) i++
})
if (i >= 2) {
this.show = true
} else {
this.show = false
}
},
// 删除已勾选
delDone() {
if (confirm('确定要删除所有已勾选的嘛?')) {
this.info.forEach(item => {
if (item.done == true) this.info = this.info.filter(item => item.done == false)
})
this.show = false
}
}
},
})
vue基本事件domo
于 2022-01-18 22:51:55 首次发布