簡體   English   中英

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 我該如何解決?

更新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是指向錯誤的事情。 此外,無需傳遞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();
  }
}

請參見如何訪問正確的this回調里面?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM