<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>computed</title>
<style>
.active {
color: rgb(142, 207, 44);
}
</style>
</head>
<body>
<div id="app">
<input type="text" v-model="username" placeholder="姓名" />
<input type="text" v-model="genboy" placeholder="性别" />
<button @click="abb">添加</button>
<button @click="del()">删除</button>
<!-- <button @click="showUser('')">全部</button>
<button @click="showUser('男')">男生</button>
<button @click="showUser('女')">女生</button> -->
<ul>
<li v-for="(user,i) in getuser" :key="i">
<input type="checkbox" v-model="user.checked" />
编号:{{i+1}} 姓名:{{user.username}} 性别:{{user.gender}}
</li>
</ul>
<button :class="{active:gender==''}" @click="gender = ''">全部</button>
<button :class="{active:gender=='男'}" @click="gender = '男'">
男生
</button>
<button :class="{active:gender=='女'}" @click="gender = '女'">
女生
</button>
全选:<input type="checkbox" v-model="checkedAll" />
</div>
</body>
<script src="js/vue.js"></script>
<script>
let users = [
{ id: 1, username: "ui", gender: "男", checked: false },
{ id: 2, username: "qw", gender: "男", checked: false },
{ id: 3, username: "er", gender: "男", checked: false },
{ id: 4, username: "ty", gender: "女", checked: false },
{ id: 5, username: "io", gender: "男", checked: false },
{ id: 6, username: "po", gender: "女", checked: false },
{ id: 7, username: "sw", gender: "男", checked: false },
];
let app = new Vue({
el: "#app",
data: {
users,
// getuser: users,
gender: "",
username: "",
genboy: "",
},
computed: {
getuser: {
get() {
if (this.gender == "") {
return this.users;
} else {
// user里的gender的值传回值 是返回符合值得所有 值
return this.users.filter((user) => user.gender == this.gender);
}
},
},
checkedAll: {
// checkedAll 他的值是由每个checked的true/false觉得的 默认为false
get() {
// every 映射返回一个新的数组 不会动原数组
return this.users.every((user) => user.checked);
},
set(newVal) {
// newVal 是个新值 原本是false 新值是true
return this.users.forEach((user) => {
user.checked = newVal;
});
},
},
},
methods: {
// showUser(gender) {
// if (gender == "") {
// this.getuser = this.users;
// } else {
// this.getuser = this.users.filter((user) => user.gender == gender);
// }
// },
abb() {
var reg = /\S/;
if (reg.test(this.username) && reg.test(this.genboy)) {
var obj = {
id: this.users.length + 1,
username: this.username,
gender: this.genboy,
checked: false,
};
// console.log(obj.name);
this.users.push(obj);
} else {
alert("不能为空");
}
this.username = this.genboy = "";
},
del() {
this.users = this.getuser.filter((user) => user.checked == false);
},
},
});
</script>
</html>
网友评论