Explain in detail the method of obtaining data by using AJAX in vue

  • 2021-07-12 05:08:48
  • OfStack

In VUE development, data can be retrieved using jquery and vue-resource. When obtaining data, 1 must give 1 initial value of data.

Look at the following example:


<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>

The initial data of data for vue must be set here, even if the data is empty at this time.

vue-resource is more appropriate when using ajax to obtain data.

Use the vue-resource code as follows:


<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>

Here we see that when setting VUE instance data, we can set vue data directly by using this. data.

When using jquery, the code is as follows:


<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>

Here, we need to assign this to _ self first, and then use it in get method of jquery, which is not as convenient as vue-resource.


Related articles: