使用Vue 编写了基础的添加删除功能遇到了一个小坑

<div id="app">
			<fieldset>
				<legend>
					Create New Person
				</legend>

				<div>
					<label>姓名:</label>
					<input v-model="new_person.name">
				</div>

				<div>
					<label>年龄:</label>
					<input v-model="new_person.age">

				</div>

				<div>
					<label>性别:</label>
					<select v-model="new_person.sex">

						<option value="男">男</option>
						<option value="女">女</option>
					</select>

				</div>
				<div id="">
					<input type="button" name="" id="" value="创建" v-on:click="Create_person" />
				</div>

			</fieldset>
			<table>
				<thead>
					<tr>
						<th>姓名</th>
						<th>年龄</th>
						<th>性别</th>
						<th>删除</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="person in people">
						<td>{{ person.name }}</td>
						<td>{{ person.age }}</td>
						<td>{{ person.sex }}</td>
						
						<td><button @click="Delete_person(index)">删除</button></td>
					</tr>
				</tbody>
			</table>
		</div>
	</body>
	

Vue代码

<script>
		var vm = new Vue({
			el: "#app",
			data: {
				new_person: {
					name: '',
					age: 0,
					sex: '男',
				},
				people: [{
						name: '1',
						age: 0,
						sex: '',
					},
					{
							name: '2',
							age: 0,
							sex: '',
						},
						{
								name: '3',
								age: 0,
								sex: '',
							}

				],
			

			},

			methods: {
				Create_person: function() {
					this.people.push(this.new_person)
					this.new_person = {
						name: '',
						age: 0,
						sex: '男',

					}
				},
				Delete_person: function(index) {
					
					this.people.splice(index, 1);
					console.log(index)

				}
			}
		})
		
	</script>

删除功能遇到点小坑,每次点击删除都会删除第一条内容
在这里插入图片描述
后来发现在下面代码处index并未获取还并未报错

<td><button @click="Delete_person(index)">删除</button></td>
// Vue 代码
	Delete_person: function(index) {
					
					this.people.splice(index, 1); //splice 命令如果传入下标将默认删除第一条
					console.log(index)

				}
			}

由此从以下代码中查找到获取下标的方法

<li v-for="(item,index)  in tabList" v-on:click="addClass(index,$event)" >{{item.title}}</li>
data里面声明:

data() {
    return {
      tabList: [
        { id: 0, title: "首页1" },
        { id: 1, title: "首页2" },
        { id: 2, title: "首页3" }
      ],
      current:0
    };
  },
  methods: {
    addClass: function(index,event) {
      this.current = index;
      //获取点击对象      
      var el = event.currentTarget;
      console.log("当前对象的内容:"+el.innerHTML);
      console.log(this.current)

然后修改代码

				<tbody>
					<tr v-for="(person,index) in people">
						<td>{{ person.name }}</td>
						<td>{{ person.age }}</td>
						<td>{{ person.sex }}</td>
						
						<td><button @click="Delete_person(index)">删除</button></td>
					</tr>
				</tbody>
Logo

前往低代码交流专区

更多推荐