VUE之信息的添加与修改

这段代码指在vue的框架下,对列表信息进行增删改查

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			window.onload = function() {
				new Vue({
					el: '#box',
					data: {
						//表格展示的数据从JSON数组中拿
						name: '',
						age: '',
						jsonArray: []
					},
					methods: {
						addObj() {
							//alert("添加");
							//做非空判断
							if (!this.name.trim() || !this.age.trim()) {
								alert("姓名和年龄不能为空")
								return;
							}
							var json = {
								'name': this.name.trim(),
								'age': this.age.trim()
							};
							//把json对象 添加到数组里面
							this.jsonArray.push(json);

							//清空旧值
							this.name = '';
							this.age = '';
						},
						//删除全部
						delAll() {
							//当列表信息为空时,提示用户不进行操作
							if (this.jsonArray.length == 0) {
								alert("没有更多信息,请添加后操作!")
							} else {
								if (window.confirm("确认要删除全部吗")) {
									this.jsonArray = [];
								}
							}
						},
						//修改
						updateName(index) {
							var name = window.prompt("请填入新的姓名");
							this.jsonArray[index].name = name;


						},
						updateAge(index) {
							var age = window.prompt("请填入新的年龄");
							this.jsonArray[index].age = age;
						},
						delSin(index) {
							if (window.confirm("确认要删除吗")) {
								this.jsonArray.splice(index, 1);
							}
						}

					}
				})
			}
		</script>
	</head>
	<body>
		<div id="box">
			<center>
				<input type="" name="" id="" value="" placeholder="请输入姓名" v-model="name" />
				<input type="" name="" id="" value="" placeholder="请输入年龄" v-model="age" />
				<input type="button" name="" id="" value="添加" @click="addObj()" />
				<br>
				<br>
				<br>
				<br>
				<table border="1" cellspacing="0" cellpadding="" width="60%" height="60%">
					<tr>
						<th>序号</th>
						<th>姓名</th>
						<th>年龄</th>
						<th>操作</th>
					</tr>
					<tr v-for="(ele,index) in jsonArray" :key="index">
						<td>{{index+1}}</td>
						<td>{{ele.name}}<a href="#" @click.prevent="updateName(index)">修改</a></td>
						<td>{{ele.age}}<a href="#" @click.prevent="updateAge(index)">修改</a></td>
						<td><button type="button" @click="delSin(index)">删除</button></td>
					</tr>
					<tr align="center">
						<td colspan="4"><button type="button" v-on:click="delAll()">全部删除</button></td>
					</tr>
				</table>
			</center>
		</div>
	</body>
</html>

你可能感兴趣的:(VUE)