vue.js刪除數(shù)組元素的方法:1、獲取數(shù)組中需要?jiǎng)h除的元素的下標(biāo);2、從該下標(biāo)開始計(jì)算,刪除長(zhǎng)度為length的元素即可。
本文操作環(huán)境:windows10系統(tǒng)、vue.js 2.9、thinkpad t480電腦。
大家記不記得有一個(gè)方法arr.splice(arr.indexOf(ele),length),這個(gè)方法可以幫助我們刪除任何js數(shù)組,非常實(shí)用。
arr.splice(arr.indexOf(ele),length)方法表示先獲取這個(gè)數(shù)組中這個(gè)元素的下標(biāo),然后從這個(gè)下標(biāo)開始計(jì)算,刪除長(zhǎng)度為length的元素。
代碼示例:
<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:'中國(guó)北京', email:'1773203101@qq.com', contacted:false, }, { name:'zhuxu', age:20, addrress:'中國(guó)上海', email:'1773203101@qq.com', contacted:false, }, ] } }, methods:{ deleteUser:function(user){ //表示先獲取這個(gè)元素的下標(biāo),然后從這個(gè)下標(biāo)開始計(jì)算,刪除長(zhǎng)度為1的元素 this.users.splice(this.users.indexOf(user),1); } } }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <!--scope只會(huì)影響到當(dāng)前組件的樣式--> <style scoped> </style>
推薦學(xué)習(xí):php培訓(xùn)