Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

js(vue axios) 异步get线上json文件数据,拿到已知嵌套对象缺无法直接取属性值

// 把url生成key
getNetworkText(url) {
  let d = url.split('.')
  let x = d[2].split('/').pop()
  return x
},
// get请求json内容到 this.getNetworkData
getNetwork(url) {
  let lastText = this.getNetworkText(url)
  // debugger
  let requestParams = {}
  const successCallBack = (res) => {
    this.getNetworkData[lastText] = {
      nodes: res.nodes,
      edges: res.edges
    }
    res
    if (res && res.code === 1) {
    }
  }
  const errCallBack = (res) => {}
  this.$get(url, requestParams, successCallBack, errCallBack)
},

// 疑问如下=============================

  this.getNetwork(res.data.Network.network_json)
  // 执行以上函数取到json数据了 下行已经打印
        console.log(this.getNetworkData)
        let a = this.getNetworkText(res.data.Network.network_json)
        // 但是直接取里面的属性 值  就会报错undefined
        // 延时2秒就好了 猜测应该是这里同步执行的缘故
        // 请问一下有更好的办法吗 已经尝试this.$nextTick不行
        setTimeout(() => {
          this.Network.nodes = this.getNetworkData[a].nodes
          this.Network.edges = this.getNetworkData[a].edges
        }, 2000)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

试试

getNetwork(url) {
    ... // 代码片段
  return this.$get(url, requestParams, successCallBack, errCallBack)// 这里return出去,this.$get返回是一个promise
},

// 同步执行,有个疑问,你这个res是哪里来的
  this.getNetwork(res.data.Network.network_json).then(()=>{
        let a = this.getNetworkText(res.data.Network.network_json)
        this.Network.nodes = this.getNetworkData[a].nodes
        this.Network.edges = this.getNetworkData[a].edges
  })
  .catch(()=>{})// 异步处理

按照官方文档的写法的话,你这个其实可以这么写

getNetwork(url) {
  let lastText = this.getNetworkText(url)
  let requestParams = {}
  return this.$get(url, requestParams).then((res)=>{
      this.getNetworkData[lastText] = {
      nodes: res.nodes,
      edges: res.edges
    };
    return this.getNetworkData[lastText]
    }).catch(()=>{
    // 异常处理
    })
},

// 假设你使用的时候是双重请求,这个res是第一层请求得到的,那还可以这么写
// 第一层请求
this.$get(url, requestParams).then(async (res)=>{
  Object.assign(this.Network ,await this.getNetwork(res.data.Network.network_json))
}).catch(()=>{
// 异常处理
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...