我是 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);
然后我得到未定义
。
我该如何解决这个问题?
更新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();
。我仍然遇到未定义
。
最佳答案
正如评论中提到的,您的 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();
}
}
关于javascript - Vuejs 2 - 从 JSON 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44148438/