【问题标题】:Vuejs 2 - Passing data from JSONVuejs 2 - 从 JSON 传递数据
【发布时间】:2017-10-24 05:04:02
【问题描述】:

我是Vuejs 的新手,所以我确定是我的代码。我有这个简单的app.vue 文件,我想从JSON 获取数据,然后根据数据设置我的菜单。我做了一个简单的测试:

export default {
  name: 'app',
  data:function(){
    return{
      menu:[]
    }
  },
  methods:{
    GetMenu:function(s){
      $.get({
    url: 'static/json/menu.json',
    success:function(res) {
      s = res.menu;
      console.log(s[0].artist);//<-- have result
    }
    })
    }
  },
  created:function(){
    this.GetMenu(this.menu);
    console.log(this.menu);//<-- have [__ob__:Observer]
  }
}

如果我运行上面的代码,我将首先从console.log(this.menu) 获得结果,即[__ob__:Observer],然后仅从console.log(s[0].artist) 获得结果,这就是我想要的。我确实尝试过:

setTimeout(function(){
console.log(this.menu);//<-- undefined
},2000);

然后我得到undefined。 我该如何解决这个问题?

更新01

我试过了:

export default {
      name: 'app',
      data:function(){
        return{
          menu:[]
        }
      },
      methods:{
        GetMenu:function(){
          $.get({
        url: 'static/json/menu.json',
        success:function(res) {
        console.log(res);//<-- result
          return res.menu;
        }
        })
        }
      },
      mounted:function(){
        this.menu = this.GetMenu();
        console.log(this.menu);//<-- undefined
      }
    }

基本上,我将GetMenu() 更改为return res.menu,然后执行this.menu = this.GetMenu();。我仍然收到undefined

【问题讨论】:

  • "this.menu" 在超时回调中没有正确的上下文。那时的“this”很可能是全局窗口。尝试将其作为 setTimeout 参数发送: $.proxy(function() { console.log(this.menu); }, this) 并查看记录的内容。
  • 我按照您的建议尝试了$.proxy,但没有任何反应。
  • 抱歉没有帮助...由于我对Vuejs一无所知,所以我会顺从其他更了解的人。伯特·埃文斯的回答看起来很有希望!

标签: javascript json vuejs2 vue-component


【解决方案1】:

正如 cmets 中所述,您的 this 指向错误的东西。另外,不需要传递this.menu

{
  name: 'app',
  data:function(){
    return{
      menu:[]
    }
  },
  methods:{
    GetMenu:function(){
      $.get({
        url: 'static/json/menu.json',
        success:function(res) {
          this.menu = res.menu;
        }.bind(this)
      })
    }
  },
  created:function(){
    this.GetMenu();
  }
}

How to access the correct this inside a callback?

【讨论】:

  • 我用你的方法,它有效。感谢您对this 的参考。无论如何,console.log() 仍然没有给我正确的结果,但数据确实显示出来了(我直接把它放到了 html 中)。
猜你喜欢
  • 2017-10-03
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2018-08-29
相关资源
最近更新 更多