vue中的父子组件,点击确定按钮,为什么新添加的编号总是重复呢?
发布于 5 年前 作者 kgong 10926 次浏览 来自 问答

用vue写了一个小功能,当点击确定按钮,为什么新添加的记录中的编号总是重复呢?

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<style type="text/css">
	table{
		border-collapse: collapse;
	}
</style>
<body>
	<div id="app">
		<add @myadd="addUser"></add>

		
		<table border="1">
			<tr>
				<th>选择</th>
				<th>编号</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>性别</th>
				<th>分数</th>
				<th>操作</th>
			</tr>
			<tr v-for="(item,index) of list" :key="item.id">
				<td><input type="checkbox" name="" :checked="item.checked" @click="handleCheck(index)"></td>
				<td>{{item.id}}</td>
				<td>{{item.name}}</td>
				<td>{{item.age}}</td>
				<td>{{item.sex}}</td>
				<td>{{item.score}}</td>
				<td><button @click="deleteItem(index)">删除</button></td>
			</tr>
		</table>
		<button @click="allDelete">全部删除</button>
	</div>

	<template id="myForm">
			<form>
				<div>				
					name:<input type="text" v-model="userInfo.name"name="">
				</div>
				<div>
					age:<input type="text" v-model="userInfo.age" name="">
				</div>
				<div>
					gender:
					<input type="radio" checked value="男" v-model="userInfo.sex"><input type="radio" value="女" v-model="userInfo.sex"></div>
				<div>
					score:<input type="text" name="" v-model="userInfo.score">
				</div>
				<button @click="handleAdd">确定</button>
			</form>
		</template>
	<script type="text/javascript">

		//添加用户的表单
		Vue.component("add",{
			template:`#myForm`,
			data:function(){
				return{
					userInfo:{}
				}
			},
			methods:{
				//添加用户
				handleAdd(e){
					this.$emit("myadd",this.userInfo)
					e.preventDefault();
				}
			},
			
		})

		var app=new Vue({
			el:"#app",
			data:{
				list:[
					{checked:false,id:1,name:"张三",age:21,sex:'男',score:78},
					{checked:false,id:2,name:"张三",age:25,sex:'男',score:79},
					{checked:false,id:3,name:"张三",age:27,sex:'男',score:83}
				],
				user:{}

			},
			methods:{
				//添加用户
				addUser(userInfo){
					this.user=userInfo;
					// this.newUser.id=this.list.length+1;
					this.user.id=this.list.length+1;
					this.list.push(this.user)
				},
				//选中与取消选中
				handleCheck(index){
					this.list[index].checked=!this.list[index].checked
				},
				//删除一项
				deleteItem(index){
					console.log(this.list[index].checked)
					if(this.list[index].checked){
						this.list.splice(index,1)
						return;
					}else{
						alert("请选中人员")
					}
				},
				//删除所有
				allDelete(){
					this.list=this.list.filter((item,index)=>{
						return item.checked==false
					})
				}

			}
		})
	</script>

</body>
</html>
回到顶部