console
var vm = new Vue({
el: "#app",
data: {
newPerson: {
name: "",
age: null,
sex: "男"
},
people: [],
isShow:false
},
mounted:function(){
this.initPeople();
},
methods: {
initPeople:function(){
if(localStorage.getItem("people") == null || localStorage.getItem("people") == "" || localStorage.getItem("people") == "[]"){
this.people = [];
this.isShow = true;
}
else{
this.people = JSON.parse(localStorage.getItem("people"));
this.isShow = false;
}
},
addPerson: function() {
if(this.newPerson.name == ""){
alert("姓名不能为空!")
}
else if (this.newPerson.age == "" || this.newPerson.age == null){
alert("年龄不能为空!")
}
else if (isNaN(this.newPerson.age)){
alert("年龄只能为数字!")
this.newPerson.age = "";
}
else{
this.people.push(this.newPerson);
localStorage.setItem("people",JSON.stringify(this.people));
this.newPerson = {
"name": "",
age: null,
sex: "男"
};
this.isShow = false;
}
},
addEnter:function(eve){
if(eve.keyCode == 13){
this.addPerson();
}
},
delPerson: function(index) {
this.people.splice(index, 1);
localStorage.setItem("people",JSON.stringify(this.people));
if(this.people == ""){
this.isShow = true;
}
}
},
filters: {
toInt(val) {
return parseInt(val)
}
}
})
<section id="app">
<fieldset>
<legend>填入信息</legend>
<div>
<label for="newName">姓名:</label>
<input type="text" id="newName" v-model="newPerson.name" />
</div>
<div>
<label for="newAge">年龄:</label>
<input type="text" id="newAge" v-model="newPerson.age" @keyup="addEnter($event)" />
</div>
<div>
<label for="newSex">性别:</label>
<select name="newSex" id="newSex" v-model="newPerson.sex" >
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<div>
<input type="button" id="addBtn" value="增加" @click="addPerson" />
</div>
</fieldset>
<table>
<tbody>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>删除</th>
</tr>
<tr v-for="(person,index) in people">
<td><span>{{index+1}}</span></td>
<td><span>{{person.name}}</span></td>
<td><span>{{person.age | toInt}}</span></td>
<td><span>{{person.sex}}</span></td>
<td><input type="button" value="×" @click="delPerson(index)" /></td>
</tr>
</tbody>
</table>
<div id="tips" v-show="isShow">暂无人员信息</div>
</section>