[英]access variable from within foreach loop in vue.js
如何從foreach循環訪問this.variable?
我有這樣
<template><div><li>{{ names }}</li></div></template>
var initData = {
names: '',
}
}
export default {
data: function () {
return initData
},
props: ['nameData'],
methods: {
printNames: function () {
let tempData = JSON.parse(JSON.stringify(this.nameData))
tempData.biglist.forEach(function (nObj) {
let cName = nObj.CeName
console.log(cName) // gives long list of names
this.names = cName
})
}
},
因此,我要在列表中添加名稱。 謝謝大家:)
您可以通過兩種方式在另一個函數范圍內訪問此函數(在本例中為forEach())。
您可以簡單地創建一個引用您的范圍的新變量,例如
printNames: function () {
let scope = this
let tempData = JSON.parse(JSON.stringify(this.nameData))
tempData.biglist.forEach(function (nObj) {
// I can access scope here
let cName = nObj.CeName
console.log(cName) // gives long list of names
this.names = cName
})
}
,您將可以在forEach中訪問此變量范圍。
或者,您可以使用箭頭功能,該功能不會創建新的作用域。 因此, this
與forEach外部相同。 這是一個例子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.