Search code examples
javascriptforeachvue.jsvuejs2var

access variable from within foreach loop in vue.js


how do I access this.variable from a foreach loop?

I have like this

<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
      })
    }
  },

So what I want is to have the names in my list. Thanks people :)


Solution

  • There is two way you can access this inside another function scope (in this case forEach() ).

    You can simple create a new variable referencing your scope, like

    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
      })
    }
    

    , and you will have access to this variable scope inside forEach.

    Or you can use arrow functions, which does not create a new scope. Therefore, same this as outside the forEach. Here is an example:

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