• 技术文章 >web前端 >js教程

    VUE中如何使用Vue-resource完成交互

    不言不言2018-06-29 15:01:33原创2628

    本篇文章主要介绍了VUE中使用Vue-resource完成交互,内容挺不错的,现在分享给大家,也给大家做个参考。

    本文介绍了VUE中使用Vue-resource完成交互,分享给大家,具体如下

    使用vue-resource

    引入vue-resource

    vue-resource就像jQuery里的$.ajax,是用来跟后端交互数据的,vue-resource是vue的一个插件,所以我们在开始使用vue之前,需要先引入vue-resource.js这个文件

    <script src='js/vue.js'></script>
    <script src='js/vue-resource.js'></script>

    基本语法

    // 基于全局Vue对象使用http
    Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
    Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
    
    
    // 在一个Vue实例内使用$http
    this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
    this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

    在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。

    options对象

    实例:

    GET请求

    在下面的实例中,我们做一个求和的功能,效果如下图:

    get方法:

    this.$http.get('/someUrl', [options]).then(function(response){  
      // 响应成功回调
    }, function(response){  
      // 响应错误回调
    });

    在该实例中,我们准备了一个php文件,该文件主要接收前台通过get传过来的参数,并计算两个参数的和,代码如下:

    <?php
      $a=$_GET['a'];
      $b=$_GET['b'];
      echo $a+$b;
    ?>

    html代码:

    <p class="container" id="box" style="margin-top:100px">
      <input type="text" name="" id="" v-model="a" />+
      <input type="text" name="" id="" v-model="b" />
      =
      <input type="button" value="求和" class="btn btn-info" @click="add()"/>
    </p>

    <script type="text/javascript">
      new Vue({
        el:"#box",
        data:{
          a:"",
          b:""
        },
        methods:{
          add:function(){
            this.$http.get("get.php",{
              "a":this.a,
              "b":this.b
            }).then(function(response){
              alert(response.data)
            },function(response){
              alert(response.status)
            }
            )
          }
        }
      })
    </script>

    说明:response是后台返回的参数,它包括以下属性:

    POST请求

    <?php
      $a=$_POST['a'];
      $b=$_POST['b'];
      echo $a+$b;
    ?>

        new Vue({
          el:"#box",
          data:{
            a:"",
            b:""
          },
          methods:{
            add:function(){
              this.$http.post("post.php",{
                "a":this.a,
                "b":this.b
              },{
                emulateJSON:true //POST请求需要将emulateJSON设置为true
              }).then(function(response){
                alert(response.data)
              },function(response){
                alert(response.status)
              }
              )
            }
          }
        })

    JSONP

    jsonp的语法跟get,post差不多,只是传递的数据不一样。接下来,我们用jsonp来完成一个百度搜索的功能。

    1.首先准备一个实例的接口,这个接口是百度的搜索接口(我们可以自己找一些接口作为测试),如下:

    https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=show

    2.准备布局

        <p class="container" id="box" style="margin-top:100px">
          <input type="text" placeholder="请输入搜索内容" />
          <ul>
            <li >22222</li>
          </ul>
          <p >暂无数据...</p>
        </p>

    3.功能描述

    当我们在搜索框中输入搜索的内容的时候,下面的列表会显示出根据我们输入的内容联想的词语。按键盘的上下键,可以上下选择列表中的词语,按enter键的时候,会执行搜索

    4.代码实现

    首先我们准备一个myData数组,存放联想的词语。t1是input框输入的值,如下

    <input type="text" placeholder="请输入搜索内容" v-model="t1" />

    data:{
      myData:[],
      t1:""
    }

    在搜索框中的输入内容的时候,执行一个方法,这个方法主要用于发送一个请求,获取输入内容的联想词语。

    <input type="text" placeholder="请输入搜索内容" v-model="t1" @keyup="search()"/>

         methods:{
            search:function(ev){this.$http.jsonp("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",{
                "wd":this.t1
              },{
                jsonp:"cb" //callback名字,默认是callback
              }).then(function(response){
                this.myData=response.data.s
              },function(response){
                alert(response.status)
              }
              )
              }
            }

    执行到这一步,列表中已经可以显示出我们搜索的联想词语了,如下图:

    下面的我们可以实现,按上下键的时候,选择词语

        <p class="container" id="box" style="margin-top:100px">
          <input type="text" v-model="t1" @keyup="search($event)" @keydown.down.prevent="changeDown($event)" @keydown.up.prevent="changeup()"/>
          <ul>
            <li v-for="(value, index) in myData" :class="{gray:index==now}">{{value}}</li>
          </ul>
          <p v-show="myData.length==0">暂无数据...</p>
        </p>

    /*data数据*/
          data:{
            myData:[],
            t1:"",
            now:-1
          }
    /*上下键的方法*/
            changeDown:function(){
                this.now++;
                if(this.now==this.myData.length){
                  this.now=-1;
                }
                this.t1=this.myData[this.now];
            },
            changeup:function(){
                this.now--;
                if(this.now==-2){
                  this.now=this.myData.length-1;
                }
                this.t1=this.myData[this.now];
            }

    完整代码:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>初识vue</title>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" rel="external nofollow" />
        <style type="text/css">
          .gray{
            background-color: gray;
          }
        </style>
      </head>
      <body>
        <p class="container" id="box" style="margin-top:100px">
          <input type="text" v-model="t1" @keyup="search($event)" @keydown.down.prevent="changeDown($event)" @keydown.up.prevent="changeup()"/>
          <ul>
            <li v-for="(value, index) in myData" :class="{gray:index==now}">{{value}}</li>
          </ul>
          <p v-show="myData.length==0">暂无数据...</p>
        </p>
      </body>
      <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
      <script src="js/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
      <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
      <script src="js/vue-resource.js" type="text/javascript" charset="utf-8"></script>
      <script type="text/javascript">
        //
        new Vue({
          el:"#box",
          data:{
            myData:[],
            t1:"",
            now:-1
          },
          methods:{
            search:function(ev){
            if(ev.keyCode==38 || ev.keyCode==40)return;
            if(ev.keyCode==13){
              window.open('https://www.baidu.com/s?wd='+this.t1);
              this.t1='';
            }          
              this.$http.jsonp("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",{
                "wd":this.t1
              },{
                jsonp:"cb" //callback名字,默认是callback
              }).then(function(response){
                this.myData=response.data.s
              },function(response){
                alert(response.status)
              }
              )
            },
            changeDown:function(){
                this.now++;
                if(this.now==this.myData.length){
                  this.now=-1;
                }
                this.t1=this.myData[this.now];
            },
            changeup:function(){
                this.now--;
                if(this.now==-2){
                  this.now=this.myData.length-1;
                }
                this.t1=this.myData[this.now];
            }        
          }
        })
      </script>
    </html>

    以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

    相关推荐:

    vue 实现剪裁图片并上传服务器的功能介绍

    Vue 实现双向绑定的方法

    以上就是VUE中如何使用Vue-resource完成交互的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:ajax-load实例 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 聊聊Node项目中怎么操作MySQL• 一文聊聊Angular中的依赖注入• react native路由跳转怎么实现• Node实战学习:浏览器预览项目所有图片• 一起聊聊var、let以及const的区别(代码示例)
    1/1

    PHP中文网