0

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.

sooon
  • 4,718
  • 8
  • 63
  • 116
  • 1
    "this.menu" within the timeout callback does not have the correct context. "this" at that point is likely the global Window. Try sending this as the setTimeout parameter: $.proxy(function() { console.log(this.menu); }, this) and see what gets logged. – pacifier21 May 24 '17 at 03:35
  • I tried `$.proxy` as you suggest but nothing happen. – sooon May 24 '17 at 03:41
  • Sorry it didn't help... Since I don't know anything about Vuejs, I will defer to others that know better. Bert Evans answer looks promising! – pacifier21 May 24 '17 at 13:24

1 Answers1

2

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?

Bert
  • 80,741
  • 17
  • 199
  • 164
  • I use your way and it works. Thanks for the reference about `this`. Anyway, the `console.log()` still did not give me the correct result but the data did show up(I put it straight into html). – sooon May 25 '17 at 02:44