11

In my Vue app, I get an XML file with Axios and use parseString to parse XML as JSON. I then need to pass the result to Vue data (this.events). My console.log shows the parsed XML as JSON, but I cannot push to Vue data inside this function.

var parseString = require('xml2js').parseString;

axios.get(`http://url.to/events.xml`)
  .then(response => {
    parseString(response.data, function (err, result) {
      console.log(result); // returns a json array
      this.events = result // nothing happens
    });        
  })
}

How do I store my JSON array to this.data in Vue?

gekkedev
  • 562
  • 4
  • 18
Filip Blaauw
  • 731
  • 2
  • 16
  • 29

2 Answers2

7

This answer is correct. However, I would just use arrow functions everywhere so the this is always the VUE class component. Also, I would check for parsing errors.

axios.get('http://url.to/events.xml')
  .then(response => {
    parseString(response.data, (err, result) => {
      if(err) {
       //Do something
      } else {
       this.events = result
     }
    });        
  })
}
oguz ismail
  • 1
  • 16
  • 47
  • 69
kimy82
  • 4,069
  • 1
  • 22
  • 25
6

Try not to use this inside parseString, maybe it's a scope issue, which means this isn't referring to the vue data object.

Try this:

axios.get('http://url.to/events.xml')
  .then(response => {
    var self = this; 
    parseString(response.data, function (err, result) {
      self.events = result
    });        
  })
}
samayo
  • 16,163
  • 12
  • 91
  • 106