vue中forEach循环的使用讲解

这篇文章主要介绍了vue中forEach循环的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

forEach循环的使用

//data为集合 data.forEach(function(item, index) { //item 就是当日按循环到的对象 //index是循环的索引,从0开始 })

使用forEach报错,this指向问题

getCrumbs(){     let crumbs = JSON.parse(localStorage.getItem( "crumbs" ));      //[Vue warn]: Error in created hook: "TypeError: Cannot set property 'manageClass' of undefined" 报错     crumbs.forEach(function(item){                    console.log(item);                             if (item.name === "staffInfo") {             this.manageClass = item.manageClass             this.infoClass = item.infoClass;          }     })      },    
crumbs.forEach(item => {     console.log(item);                         if (item.name === "staffInfo") {         this.manageClass = item.manageClass         this.infoClass = item.infoClass;      } })

每一个用function声明的函数在调用时都会在函数内创建自己的this。this一般是函数所操作的对象。如果没有操作的对象。this在"use strict";严格模式下是 undefined,非严格模式下是 window。
也就是说,function声明的函数总是有自己的this。从而遮盖外层作用域中的this。

如果用es6的箭头函数()=>{}就没有自己的this。在箭头函数()=>{}中访问this,是访问外层作用域中的this

 getCrumbs(){ let crumbs = JSON.parse(localStorage.getItem( "crumbs" )); //[Vue warn]: Error in created hook: "TypeError: Cannot set property 'manageClass' of undefined" 报错 // crumbs.forEach(function(item){ crumbs.forEach(item => { console.log(item); if (item.name === "staffInfo") { this.manageClass = item.manageClass this.infoClass = item.infoClass; } }) //  或者使用for循环 for (let i = 0; i 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。

以上就是vue中forEach循环的使用讲解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Vue.js 教程