Parse XML from Axios response, pushing to Vue data array

别等时光非礼了梦想. 提交于 2020-01-22 09:43:07

问题


In my Vue app, I get a 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 to store my JSON array to this.data in Vue?


回答1:


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



回答2:


Answer above 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
     }
    });        
  })
}


来源:https://stackoverflow.com/questions/48788185/parse-xml-from-axios-response-pushing-to-vue-data-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!