在VUE开发时,数据可以使用jquery和vue-resource来获取数据。在获取数据时,一定需要给一个数据初始值。
看下例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<script type=
"text/javascript"
>
new
Vue({
el:
'#app'
,
data:{data:
""
},
created:
function
(){
var
url=
"json.jsp"
;
var
_self=
this
;
$.get(url,
function
(data){
_self.data=eval(
"("
+ data +
")"
);
})
/*
this.$http.get(url).then(function(data){
var json=data.body;
this.data=eval("(" + json +")");
},function(response){
console.info(response);
})*/
}
});
</script>
|
这里必须设置 vue的data的初始数据,即使此时数据为空。
在使用ajax获取数据时,使用vue-resource 更加合适。
使用vue-resource代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<script type=
"text/javascript"
>
new
Vue({
el:
'#app'
,
data:{data:
""
},
created:
function
(){
var
url=
"json.jsp"
;
this
.$http.get(url).then(
function
(data){
var
json=data.body;
this
.data=eval(
"("
+ json +
")"
);
},
function
(response){
console.info(response);
})
}
});
</script>
|
这里我们看到设置VUE实例数据时,直接使用 this.data 就可以设置vue的数据了。
使用jquery的时候,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<script type=
"text/javascript"
>
new
Vue({
el:
'#app'
,
data:{data:
""
},
beforeCreate:
function
(){
var
url=
"json.jsp"
;
var
_self=
this
;
$.get(url,
function
(data){
_self.data=eval(
"("
+ data +
")"
);
})
}
});
</script>
|
这里在需要先将 this 赋值给 _self ,让后在jquery的get方法中进行使用,这样使用起来没有vue-resource方便。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。