在VUE開發(fā)時,數(shù)據(jù)可以使用jquery和vue-resource來獲取數(shù)據(jù)。在獲取數(shù)據(jù)時,一定需要給一個數(shù)據(jù)初始值。
看下例:
<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的初始數(shù)據(jù),即使此時數(shù)據(jù)為空。
在使用ajax獲取數(shù)據(jù)時,使用vue-resource 更加合適。
使用vue-resource代碼如下:
<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實例數(shù)據(jù)時,直接使用 this.data 就可以設置vue的數(shù)據(jù)了。
使用jquery的時候,代碼如下:
<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方便。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答