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)表達(dá)式實戰(zhàn)案例
- Vue中實現(xiàn)v-for循環(huán)遍歷圖片的方法
- vue中的循環(huán)遍歷對象、數(shù)組和字符串
- vue實現(xiàn)列表無縫循環(huán)滾動
- Vue3基礎(chǔ)篇之常用的循環(huán)示例詳解
相關(guān)文章
手動實現(xiàn)vue2.0的雙向數(shù)據(jù)綁定原理詳解
這篇文章主要給大家介紹了關(guān)于手動實現(xiàn)vue2.0的雙向數(shù)據(jù)綁定原理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
vue-cli webpack模板項目搭建及打包時路徑問題的解決方法
這篇文章主要介紹了vue-cli webpack模板項目搭建以及打包時路徑問題的解決方法,需要的朋友可以參考下2018-02-02
如何用vue3+Element?plus實現(xiàn)一個完整登錄功能
要實現(xiàn)用戶的登錄功能,可以使用Vue3和Element?Plus,下面這篇文章主要給大家介紹了關(guān)于如何基于Vue3和Element?Plus組件庫實現(xiàn)一個完整的登錄功能,文中提供了詳細(xì)的代碼示例,需要的朋友可以參考下2023-10-10

