Vuejs 2 - Passing data from JSON

2019-09-16 08:35发布

问题:

I am new in Vuejs so I am sure is my code. I have this simple app.vue file and I want to get the data from JSON and then setup my menu based on the data. I do a simple test:

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]
  }
}

If I run the code above I will get the result from console.log(this.menu) first, which is [__ob__:Observer], then only result from console.log(s[0].artist), which is what I want. I did try:

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

Then I get undefined. How can I resolve this?

Update01

I tried:

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

Basically, I change the GetMenu() to return res.menu then do this.menu = this.GetMenu();. I am still getting undefined.

回答1:

As mentioned in the comments, your this is pointing to the wrong thing. Additionally, there is no need to pass 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();
  }
}

See How to access the correct this inside a callback?