使用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代码:

<div 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()"/>
</div>
<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.准备布局

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

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

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

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

        <div 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>
        </div>
/*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"/>
        <style type="text/css">
            .gray{
                background-color: gray;
            }
        </style>
    </head>
    <body>
        <div 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>
        </div>
    </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>

使用Vue-resource完成交互的更多相关文章

  1. vue前后台数据交互vue-resource文档

    地址:https://segmentfault.com/a/1190000007087934 Vue可以构建一个完全不依赖后端服务的应用,同时也可以与服务端进行数据交互来同步界面的动态更新. Vue通 ...

  2. vue教程1-09 交互 vue实现百度下拉列表

    vue教程1-09 交互 vue实现百度下拉列表 <!DOCTYPE html> <html lang="en"> <head> <met ...

  3. vue教程1-08 交互 get、post、jsonp

    vue教程1-08 交互 get.post.jsonp 一.如果vue想做交互,引入: vue-resouce 二.get方式 1.get获取一个普通文本数据: <!DOCTYPE html&g ...

  4. vue resource 携带cookie请求 vue cookie 跨域

    vue resource 携带cookie请求 vue cookie 跨域 1.依赖VueResource 确保已安装vue-resource到项目中,找到当前项目,命令行输入: npm instal ...

  5. Vue - 与后端交互

    零:与后端交互 - ajax 版本1 - 出现了跨域问题 前端:index.html <!DOCTYPE html> <html lang="en"> &l ...

  6. Vue之前后端交互

    Vue之前后端交互 一.前后端交互模式 接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环境是「单线程」 所谓单线程,是指JS引擎中负责 ...

  7. 三、vue前后端交互(轻松入门vue)

    轻松入门vue系列 Vue前后端交互 六.Vue前后端交互 1. 前后端交互模式 2. Promise的相关概念和用法 Promise基本用法 then参数中的函数返回值 基于Promise处理多个A ...

  8. Vue Resource root options not used?

    I specify a root options in my Vue-Resource in my main.js file, but when I do the request, it does n ...

  9. vue -resource 文件提交提示process,或者拦截处理

    this.$http.post('url',fd||data,{emulateJSON:true}).then(fn(res){},fn(res){}) process成功案例 _self.$http ...

  10. vue resource 携带cookie请求 vue cookie 跨域(六)

    1.依赖VueResource  确保已安装vue-resource到项目中,找到当前项目,命令行输入: npm install vue-resource --save 在主方法添加 过滤 Vue.h ...

随机推荐

  1. {网络编程}和{多线程}应用:基于UDP协议【实现多发送方发送数据到同一个接收者】--练习

    要求: 使用多线程实现多发送方发送数据到同一个接收者 代码: 发送端:可以在多台电脑上启动发送端,同时向接收端发送数据 注意:匹配地址和端口号 package com.qf.demo; import ...

  2. RPM安装软件

    RMP:rpm命令详解.注意事项.rpm仓库.安装实例.srpm:源码rpm RPM Package Manager 由Red Hat公司提出,被众多Linux发行版所采用: 建立统一的数据库文件,详 ...

  3. 如何添加自己封装的代码到Cocoapod

    这两天学习了如何添加自己封装的代码到Cocoapod中 以下是我这两天遇到的各种坑: 旧的方法:  http://my.oschina.net/u/727843/blog/392784 这个看看可以大 ...

  4. FastReport.NET 中使用二维码

    FastReport.net 是一个比较好用的报表控件,在编辑器中编辑以后 可以直接在vs 中引用. 最近在研究fastreport 现在讲解一下 如何使用它的二维码. fastreport 没有单独 ...

  5. python http长连接客户端

    背景: 线上机器,需要过滤access日志,发送给另外一个api 期初是单进程,效率太低,改为多进程发送后,查看日志中偶尔会出现异常错误(忘记截图了...) 总之就是端口不够用了报错 原因: 每一条日 ...

  6. ssh隧道

    最近有需求使用ssh隧道,顺便研究了下,以下记录一下大概说明 ssh隧道顾名思义在可以通过ssh连接的server之间建立加密隧道,常用于突破网络限制 常用三种端口转发模式:本地端口转发,远程端口转发 ...

  7. 使用HttpClient 调用Web Api

    C#4.5 添加了异步调用Web Api . 如果你的项目是4.5以上版本,可以直接参考官方文档. http://www.asp.net/web-api/overview/web-api-client ...

  8. Nmap脚本引擎原理

    Nmap脚本引擎原理 一.NSE介绍 虽然Nmap内嵌的服务于版本探测已足够强大,但是在某些情况下我们需要多伦次的交互才能够探测到服务器的信息,这时候就需要自己编写NSE插件实现这个功能.NSE插件能 ...

  9. IIS虚拟目录与UNC路径权限初探

    最近在一个项目中涉及到了虚拟目录与UNC路径的问题,总结出来分享给大家. 问题描述 某客户定制化项目(官网),有一个图片上传的功能.客户的Web机器有10台,通过F5负载均衡分摊请求. 假设这10台机 ...

  10. jQuery时间日期插件laydate,兼容bootstrap

    解压后,将laydate整个文件放至您项目的任意目录,不要移动其文件结构,它们具有完整的依赖体系. 使用只需在页面引入laydate.js即可. 如果您的网站的js采用合并或模块加载,您需要打开lay ...