Vuejs从数组中删除元素的示例代码

Vuejs从数组中删除元素

使用方法:arr.splice(arr.indexOf(ele),length):表示先获取这个数组中这个元素的下标,然后从这个下标开始计算,删除长度为length的元素 这种删除方式适用于任何js数组

eg:

<template>
 <div class="users">
	<button type="button" class="btn btn-danger" v-on:click="deleteUser(user)"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除</button>	
 </div>
</template>

<script>
//引入jquery

export default {

 data(){
	return {
	
	users:[
	{
	name:'zx',
	age:18,
	addrress:'江苏南京',
	email:'1773203101@qq.com',
	contacted:false,
	},
	{
	name:'zhiyi',
	age:19,
	addrress:'中国北京',
	email:'1773203101@qq.com',
	contacted:false,
	},
	{
	name:'zhuxu',
	age:20,
	addrress:'中国上海',
	email:'1773203101@qq.com',
	contacted:false,
	},
	]
	}
	},
	methods:{
	deleteUser:function(user){
	//表示先获取这个元素的下标,然后从这个下标开始计算,删除长度为1的元素
	this.users.splice(this.users.indexOf(user),1);
	}
	}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--scope只会影响到当前组件的样式-->
<style scoped>
</style>

补充:vue 删除数组中的某一条数据

一、删除普通数组

let arr = [1,2,3,4,5];

//方法一
let index = arr.indexOf('3');
arr.splice(index, 1)
//打印结果 [1,2,4,5]
//方法二
let index = arr .findIndex(item => {
 if (item == '3') {
 return true
 }
 })
arr.splice(index, 1)
//打印结果 [1,2,4,5]

二、删除数组对象

let arr = [
 {
 id:1,
 name:'张三'
 },
 {
 id:2,
 name:'李四'
 },
 {
 id:3,
 name:'王二'
 },
 {
 id:4,
 name:'麻子'
 },
];
let id1 = arr.findIndex(item => {
 if (item.id == '3') {
 return true
 }
 })
 arr.splice(id1, 1)

三、欢迎添加更多方法,以上是我觉得最简单的方法

作者:ZNineSun原文地址:https://blog.csdn.net/zhiyikeji/article/details/84202829

%s 个评论

要回复文章请先登录注册