Vuejs 2 - 从 JSON 传递数据

Vuejs 2 - Passing data from JSON

我是 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。 我该如何解决这个问题?

Update01

我试过了:

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 指向错误的内容。此外,无需传递 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?