Vue-增加、删除、查询数据并在页面中显示(包含数组的filter方法)

本文介绍了如何在Vue应用中利用filter方法进行数据的增删查操作,详细讲解了如何通过回调函数筛选满足特定条件的数组元素,并将其在页面上展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<div id="app">
	<label>
		Id:
		<input type="text" v-model="id" />
	</label>
	
	<label>
		品牌:
		<input type="text" v-model="name" />
	</label>
	
	<button type="button" @click="add">添加</button>
	
	<br />
	<label>
		根据品牌名称搜索:
		<input type="text" v-model="search" @keyup="searchName" />
	</label>
	
	<table cellpadding="0" cellspacing="0" border="1">
		<thead>
			<tr>
				<th>ID</th>
				<th>创建时间</th>
				<th>汽车品牌</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="(item, i) in searchName()" :key="item.id">
				<td>{{item.id}}</td>
				<td>{{item.addDate}}</td>
				<td>{{item.name}}</td>
				<td @click="del(i)">删除</td>
			</tr>
		</tbody>
	</table>
</div>
var vm = new Vue({
	el: '#app',
	data: {
		id: '',
		name: '',
		search: '',
		cars: [
			{id: 1, addDate: new Date(), name: '宝马'},
			{id: 2, addDate: new Date(), name: '奔驰'}
		]
	},
	methods: {
		add(){
			// console.log(this.cars);
			var objCar = {id: this.id, addDate: new Date(), name: this.name};
			this.cars.push(objCar);
			this.id = this.name = '';
		},
		searchName(){
			// var newCars = [];
			// this.cars.forEach(item => {
			// 	// if(item.name.indexOf(this.search) != -1){
			// 	// 	newCars.push(item);
					
			// 	// }
				
			// 	if(item.name.includes(this.search)) newCars.push(item);
			// 	// console.log(item.name.includes(this.search));
				
			// });
			// return newCars;
			
			
			// 数组的filter方法,作用是循环指定的数组,并把满足回调函数中指定条件的项返回,得到新的数组
			// var newCars = this.cars.filter(item => {
			// 	return item.name.includes(this.search);
			// });
			// return newCars;
			
			return this.cars.filter(item => item.name.includes(this.search));
		},
		del(i){
			// this.cars.some((item, i) => {
			// 	if(item.id == id){
			// 		this.cars.splice(i,1);
			// 	}
			// })
			this.cars.splice(i,1);
			return this.cars;
		}
	}
})

数组的filter方法,作用是循环指定的数组,并把满足回调函数中指定条件的项返回,得到新的数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值