如何在Vue中遍历数组

  介绍

本篇文章给大家分享的是有关如何在Vue中遍历数组,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

<强> 1,foreach

foreach循环对不能使用回报来停止循环

,搜索(关键字){   ,,,,var  newList =, []   ,,,,this.urls.forEach (item =祝辞,{   ,,,,,如果(item.name.indexOf(关键字),!=,1){   ,,,,,,newList.push(项)   ,,,,,}   ,,,,})   ,,,,return  newList   ,,,}

<强> 2,过滤器

项对象就是遍历数组中的一个元素,包括是es6中的新方法,在搜索方法中直接返回新数组

,搜索(关键字){   ,,,,return  this.urls.filter (item =祝辞{   ,,,,,如果(item.name.includes(关键字)){   ,,,,,,return 项目   ,,,}   })才能   以前,}

<强> 3,findIndex

返回真正的后指数就可以获取到匹配的元素在进行删除

德尔(行){   ,,,,确认美元。(“确定要删除吗?“,,“删除“),然后(action=祝辞{   ,,,,var  index =, this.urls.findIndex (item =祝辞,{   ,,,,,如果(item.name ==, row.name) {   ,,,,,,return 真实;   ,,,,,}   ,,,,})   ,,,,this.urls.splice(指数,1)   });

<强> 4,一些

如果匹配成功就返回true跳出一些的循环

德尔(行){   ,,,确认美元。(“确定要删除吗?“,,“删除“),然后(action=祝辞{   ,,,,,this.urls.some((我)项目,,,=在{   ,,,,,如果(item.name ==, row.name) {   ,,,,,,this.urls.splice(我,1)   ,,,,,,return 真实;   ,,,,,}   ,,,,}),   ,,});   }

5,上例子,在一个vue的数据中存入一个固定的数组,对数组进行遍历,实现搜索功能,删除功能

在el-table中:数据中绑定一个方法,方法中对固定的数组url进行遍历,返回一个新的数组实现搜索功能

& lt; template>   & lt;才能div>   ,,& lt; label 比;   ,,搜索关键字:   ,,& lt; input 类型=皌ext",类=癴orm-control", v模型=発eyword"比;   & lt;才能/label>   ,,,& lt; el-table : data=https://www.yisu.com/zixun/八阉?关键字)”大?靶 ?条纹=" true ":边境=" true " @select="选择" @select-all="选择">            <模板slot-scope=安邸?    {{slot.row.name}}                     <模板slot-scope=安邸?                     
     <>脚本   出口默认{   数据(){   返回{   关键字:”,   选择:[],   url: [{   名称:“新浪”,   url:“http://www.sina.com”,   类型:“资讯”,   国家:“中国”   },   {   名称:“腾讯”,   url:“http://www.tencent.com”,   类型:“聊天”,   国家:“中国”   },   {   名称:“谷歌”,   url:“http://www.google.com”,   类型:“资讯”,   国家:“美国”   },   {   名称:“韬睿”,   url:“http://www.51i-star.com”,   类型:“教育”,   国家:“中国”   }   ]   };   },   方法:{   德尔(行){   这一点。确认美元(“确定要删除吗?”,“删除”),然后(action=> {/* this.urls。一些((项目,i)=> {   如果(item.name==row.name) {   this.urls。拼接(我,1)   返回true;   }   }) */var=this.urls指数。findIndex(项=> {   如果(item.name==row.name) {   返回true;   }   })   this.urls。拼接(指数(1)   });   },   选择(选择,行){   这一点。选择=选择;   },   batchDelete () {   这一点。确认美元(“确定要删除吗?”,“删除”)   不要犹豫(action=> {   我(var=this.urls。长度- 1;我>=0;我(){   (var j=this.selections。长度- 1;j>=0;j () {   如果(this.urls[我]. name==this.selections [j] . name) {   this.urls。拼接(我,1);   打破;   }   }   }   })   .catch(错误=> {   警报(错误);   美元。消息(“删除取消”);   });   },   搜索(关键字){/* var newList=[]   this.urls。forEach(项=> {   如果(item.name.indexOf(关键字)!=1){   newList.push(项)   }   })   返回newList */this.urls返回。过滤器(项=> {   如果(item.name.includes(关键字)){   返回项目   }   })   }   }   }>

如何在Vue中遍历数组