简体   繁体   中英

Vuejs 2 - Passing data from JSON

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 .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM