【发布时间】:2017-10-24 05:04:02
【问题描述】:
我是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.menu" 在超时回调中没有正确的上下文。那时的“this”很可能是全局窗口。尝试将其作为 setTimeout 参数发送: $.proxy(function() { console.log(this.menu); }, this) 并查看记录的内容。
-
我按照您的建议尝试了
$.proxy,但没有任何反应。 -
抱歉没有帮助...由于我对Vuejs一无所知,所以我会顺从其他更了解的人。伯特·埃文斯的回答看起来很有希望!
标签: javascript json vuejs2 vue-component