在 vue.js 的 foreach 循环中访问变量
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 内部的这个变量范围。
或者您可以使用箭头函数,它不会创建新的作用域。因此,与 forEach 之外的 this
相同。这是一个例子:
如何从 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 内部的这个变量范围。
或者您可以使用箭头函数,它不会创建新的作用域。因此,与 forEach 之外的 this
相同。这是一个例子: