【问题标题】:Cannot access json data in component无法访问组件中的 json 数据
【发布时间】:2019-08-21 23:38:51
【问题描述】:

我正在尝试从 XMLHttpRequest 获取 json 数据,它运行良好,因此我在控制台中看到了数据。但是应该显示这些数据的组件没有显示任何...有什么问题吗?也许在mounted()中调用函数是错误的?我也在 created() 中调用它,但没有任何改变......有什么想法吗?

在脚本中

    data(){
       return{
        json: {}
       }
    }

    mounted(){
     var gsRef = firebase.storage().refFromURL('XXXXXXXXX')
   gsRef.child(firebase.auth().currentUser.uid+'.json').getDownloadURL().then(function(url){
            var xhr = new XMLHttpRequest()
            xhr.responseType = 'json'
            xhr.onload = function() {
              this.json = xhr.response
              console.log(this.json.user) //works shows the data!
            }
            xhr.open('GET',url)
            xhr.send()
          })
      }

在模板中

<h1>{{json.user}}</h1> //doenst work. Cannot access data

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    "this" 可能指的是错误的上下文(即不是 vue 实例)。尝试在调用 firebase 之前保存对正确 this 的引用,例如 const self = this,然后使用 self.json 设置数据。

    mounted(){
         var self = this
         var gsRef = firebase.storage().refFromURL('XXXXXXXXX')
       gsRef.child(firebase.auth().currentUser.uid+'.json').getDownloadURL().then(function(url){
                var xhr = new XMLHttpRequest()
                xhr.responseType = 'json'
                xhr.onload = function() {
                  self.json = xhr.response
                  console.log(self.json.user) //works shows the data!
                }
                xhr.open('GET',url)
                xhr.send()
              })
          }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多