Vuejs 2 - 从 JSON 传递数据 [英] Vuejs 2 - Passing data from JSON
问题描述
我是 Vuejs
的新手,所以我确定是我的代码.我有这个简单的 app.vue
文件,我想从 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]
}
}
如果我运行上面的代码,我将首先从console.log(this.menu)
得到结果,即[__ob__:Observer]
,然后只有结果来自 console.log(s[0].artist)
,这就是我想要的.我确实尝试过:
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);
然后我得到 undefined
.我该如何解决?
Then I get undefined
.
How can I resolve this?
更新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
.
Basically, I change the GetMenu()
to return res.menu
then do this.menu = this.GetMenu();
. I am still getting undefined
.
推荐答案
正如评论中提到的,你的 this
指向了错误的东西.另外,不需要传递this.menu
.
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?
这篇关于Vuejs 2 - 从 JSON 传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!