<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<div>
ID: <input type="text" v-model="id">
<br>
姓名: <input type="text" v-model="name">
<br>
性别: <input type="text" v-model="id">
<button type="button" @click="add()">添加</button>
</div>
<table>
<thead>
<tr>
<th>ID:</th>
<th>姓名:</th>
<th>性别:</th>
<th>生日:</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for= "person in people">
<td>{{person.id}}</td>
<td>{{person.name}}</td>
<td>{{person.sex}}</td>
<td>{{person.birthday|formatDate}}</td>
<td><button @click=del(person.id) >删除当前用户</button></td>
</tr>
</tbody>
</table>
</div>
<script src="js/vue.js"></script>
<script>
Vue.filter('formatDate', data => {
if (data == null || data == '') {
return '';
}
var date = new Date(data);
var dateStr = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
return dateStr;
});
var vm = new Vue({
el:'#app',
/*会在vm创建完成后执行*/
created() {
var people = JSON.parse(localStorage.getItem('people')||'[]')
this.people = people;
},
data: {
/*存了所有人员*/
id:null,
name:null,
sex:null,
people:[
// {id:123,name:'hh',sex:'n'},
// {id:124,name:'hh',sex:'n'}
]
},
methods: {
/*将用户输入的信息插入到data中的人员数组*/
add() {
/*获取用户输入的信息*/
/*将获取到的信息插入people*/
var person = {
id:this.id,
name:this.name,
sex:this.sex,
birthday:new Date()
}
this.people.push(person);
localStorage.setItem("people",JSON.stringify(this.people));
},
del(id) {
this.people.some((person,i) =>{
/*箭头函数中的this就是其外部函数的this*/
if(person.id == id) {
/*利用下标i删除people中的当前记录*/
this.people.splice(i,1);
/*localStorage只能存字符串,所以想把person存入的话,
所以我们可以将person序列化*/
localStorage.setItem("people",JSON.stringify(this.people));
return true;
}
})
}
}
})
</script>
</body>
</html>
02-01
7675
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)