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

时间:2018-04-25 12:57:32

标签: javascript foreach vue.js vuejs2 var

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

所以我想要的是在我的列表中有名字。谢谢大家:)

1 个答案:

答案 0 :(得分:3)

有两种方法可以在另一个函数范围内访问它(在本例中为forEach())。

您可以简单地创建一个引用范围的新变量,例如

structure(c(6, 2, 4, 3, 5, 1, 7, 3, 7, 2, 5, 1, 6, 4, 4, 3, 2, 
6, 1, 5, 7, 1, 5, 2, 7, 4, 6, 3, 6, 2, 4, 7, 3, 5, 1, 2, 3, 7, 
1, 5, 6, 4, 5, 1, 2, 6, 4, 3, 7, 1, 3, 2, 4, 7, 5, 6, 3, 1, 6, 
5, 7, 2, 4, 5, 6, 7, 2, 4, 3, 1, 6, 5, 1, 3, 4, 7, 2, 2, 4, 1, 
3, 7, 6, 5, 5, 1, 7, 2, 4, 6, 3, 1, 5, 2, 4, 7, 6, 3), .Dim = c(7L, 
14L), .Dimnames = list(c("SerCli", "Recensioni", "Spedizione", 
"SafePay", "EasyBuy", "Garanzia", "Prezzo"), NULL))

,您将可以访问forEach中的此变量范围。

或者您可以使用箭头功能,但不会创建新范围。因此,与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 }) } 相同。这是一个例子:

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

相关问题