问题:从 vue.js 的 foreach 循环中访问变量

如何从 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
      })
    }
  },

所以我想要的是在我的列表中有这些名字。谢谢人们:)

解答

有两种方法可以在另一个函数范围内访问 this (在本例中为 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相同。这是一个例子:

http://jsfiddle.net/2eAqE/1149/

Logo

前往低代码交流专区

更多推荐