初次使用 vue 的时候难免出问题, 比如 vue 通过 Ajax 获取数据的时候, 如果不小心就容易出问题, 本文就来为大家介绍一些在 vue 通过 Ajax 获取数据时容易遇到的错误.
在 vue 开发时, 数据可以使用 jQuery 和 vue-resource 来获取数据. 在获取数据时, 一定需要给一个数据初始值.
看下例:
- <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 代码如下:
- <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 的时候, 代码如下:
- <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 方便, 另外除了 jQuery,axios 也需要先把 this 赋值给_self.
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/vue-js/17568.html