【问题标题】:access variable from within foreach loop in vue.js从 vue.js 的 foreach 循环中访问变量
【发布时间】:2018-04-25 12:57:32
【问题描述】:

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

所以我想要的是在我的列表中包含这些名称。谢谢大家:)

【问题讨论】:

  • 分享任何现场 sn-p/ 演示?您提供的代码不清楚。
  • 你可以在函数var me= this之前定义,在forEach()里面你可以使用me.variable来访问。
  • 1. names 应该设置什么 this.names 属性? 2. 请注意,它会被反复覆盖,就像您在forEach 回调中一样。 3. 请注意this 将是undefined(严格模式)或全局对象(松散模式),因为您使用传统函数作为回调,而不是指定thisforEach 应该使用。您可能想要一个箭头功能,但从您所展示的内容中无法说明。
  • T.J 克劳德。是的,我应该将所有名称都放入对象值中,对吗?然后用 v-for 循环让他们每个人都这样做我不确定如何做到这一点(但)

标签: javascript foreach vue.js vuejs2 var


【解决方案1】:

有两种方法可以在另一个函数范围内访问 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 中的这个变量范围。

或者您可以使用箭头函数,它不会创建新范围。因此,this 与 forEach 外部相同。这是一个例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2012-09-26
    相关资源
    最近更新 更多