从 Axios 响应解析 XML,推送到 Vue 数据数组 [英] Parse XML from Axios response, pushing to Vue data array

查看:54
本文介绍了从 Axios 响应解析 XML,推送到 Vue 数据数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Vue 应用程序中,我使用 Axios 获取一个 XML 文件,并使用 parseString 将 XML 解析为 JSON.然后我需要将 result 传递给 Vue 数据(this.events).我的 console.log 将解析的 XML 显示为 JSON,但我无法在此函数内推送到 Vue 数据.

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

如何将我的 JSON 数组存储到 Vue 中的 this.data?

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

推荐答案

尽量不要在 parseString 内部使用 this,可能是范围问题,也就是 this 不是指 vue 数据对象.

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

试试这个:

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

这篇关于从 Axios 响应解析 XML,推送到 Vue 数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆