在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方便。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。