vue中forEach循環(huán)的使用講解
forEach循環(huán)的使用
//data為集合
data.forEach(function(item, index) {
//item 就是當(dāng)日按循環(huán)到的對象
//index是循環(huán)的索引,從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聲明的函數(shù)在調(diào)用時都會在函數(shù)內(nèi)創(chuàng)建自己的this。this一般是函數(shù)所操作的對象。如果沒有操作的對象。this在"use strict";嚴(yán)格模式下是 undefined,非嚴(yán)格模式下是 window。
也就是說,function聲明的函數(shù)總是有自己的this。從而遮蓋外層作用域中的this。
如果用es6的箭頭函數(shù)()=>{}就沒有自己的this。在箭頭函數(shù)()=>{}中訪問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循環(huán)
for (let i = 0; i < crumbs.length; i++) {
if (crumbs[i].name === "staffInfo") {
this.manageClass = crumbs[i].manageClass
this.infoClass = crumbs[i].infoClass;
}
}
}, 以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- vue-router使用next()跳轉(zhuǎn)到指定路徑時會無限循環(huán)問題
- vue循環(huán)中調(diào)用接口-promise.all();按順序執(zhí)行異步處理方式
- vue中v-for循環(huán)數(shù)組,在方法中splice刪除數(shù)組元素踩坑記錄
- vue?循環(huán)動態(tài)設(shè)置ref并獲取$refs方式
- vue如何在for循環(huán)中設(shè)置ref并獲取$refs
- vue中v-model如何綁定多循環(huán)表達式實戰(zhàn)案例
- Vue中實現(xiàn)v-for循環(huán)遍歷圖片的方法
- vue中的循環(huán)遍歷對象、數(shù)組和字符串
- vue實現(xiàn)列表無縫循環(huán)滾動
- Vue3基礎(chǔ)篇之常用的循環(huán)示例詳解
相關(guān)文章
Vue中使用 setTimeout() setInterval()函數(shù)的問題
這篇文章主要介紹了Vue中使用 setTimeout() setInterval()函數(shù)的問題 ,需要的朋友可以參考下2018-09-09
vue路由history模式頁面刷新404解決方法Koa?Express
這篇文章主要為大家介紹了vue路由history模式頁面刷新404解決方法(Koa?Express)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
VUE+ElementUI下載文件的幾種方式(小結(jié))
本文主要介紹了VUE+ElementUI下載文件的幾種方式(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
Vue學(xué)習(xí)筆記進階篇之vue-cli安裝及介紹
這篇文章主要介紹了Vue學(xué)習(xí)筆記進階篇之vue-cli安裝及介紹,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07

