vue请求后台接口 方法

ue不支持直接发送AJAX请求,需要使用vue-resource、axios等插件实现。

一.使用axios发送AJAX请求:

1.安装axios并引入:

1)npm install axios -S (直接下载axios组件,下载完毕后axios.js就存放在node_modules\axios\dist中),首先在 main.js 中引入 axios:在此文件加入import axios from 'axios',如果在其它的组件中无法使用 axios 命令。可以将 axios 改写为 Vue 的原型属性:Vue.prototype.$http=axios,在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 this.$http命令。

 2)网上直接下载axios.min.js文件,通过script src的方式进行文件的引入

2.发送请求:

1)get请求使用格式:

a:axios([options]) (这种格式直接将所有数据写在options里,options其实是个字典)

b:axios.get(url[,options]);

<script>     
    new Vue({
             el:'#itany',
             data:{
                user:{
                     name:'alice',
                     age:19
                    },
                },
                methods:{
                    send(){
                        axios({//格式a
                            method:'get',
                            url:'http://www.baidu.com?name=tom&age=23'
                        }).then(function(resp){
                            console.log(resp.data);
                        }).catch(resp => {
                            console.log('请求失败:'+resp.status+','+resp.statusText);
                        });
                    },
                    sendGet(){//格式b
                        axios.get('server.php',{
                            params:{
                                name:'alice',
                                age:19
                            }
                        })
                        .then(resp => {
                            console.log(resp.data);
                        }).catch(err => {             //
                            console.log('请求失败:'+err.status+','+err.statusText);
                        });
                    },
                }
            });
    </script>

2)post请求格式:

a:axios.post(url,data,[options]);

new Vue({
                el:'#itany',
                data:{
                    user:{
                        name:'alice',
                        age:19
                    },
                },
                methods:{
                    sendPost(){
                        // axios.post('server.php',{
                        //         name:'alice',
                        //         age:19
                        // }) //该方式发送数据是一个Request Payload的数据格式,一般的数据格式是Form Data格式,所有发送不出去数据
                        // axios.post('server.php','name=alice&age=20&') //方式1通过字符串的方式发送数据
                        axios.post('server.php',this.user,{  //方式2通过transformRequest方法发送数据,本质还是将数据拼接成字符串
                            transformRequest:[
                                function(data){
                                    let params='';
                                    for(let index in data){
                                        params+=index+'='+data[index]+'&';
                                    }
                                    return params;
                                }
                            ]
                        })
                        .then(resp => {
                            console.log(resp.data);
                        }).catch(err => {
                            console.log('请求失败:'+err.status+','+err.statusText);
                        });
                    },
                }
            });

3)发送跨域请求:

a:须知:axios本身并不支持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加支持发送跨域请求,所以只能使用第三方库

b:使用vue-resource发送跨域请求

c: 安装vue-resource并引入    

   npm info vue-resource           #查看vue-resource 版本信息
      cnpm install vue-resource -S #等同于cnpm install vue-resource -save

d: 基本使用方法(使用this.$http发送请求) 

    this.$http.get(url, [options])

    this.$http.head(url, [options])

    this.$http.delete(url, [options])

    this.$http.jsonp(url, [options])

    this.$http.post(url, [body], [options])

    this.$http.put(url, [body], [options])

    this.$http.patch(url, [body], [options]) 

二.vue-resource发送请求:

1.安装引入vue-resource方式:

1)npm install axios -S (直接下载axios组件,下载完毕后axios.js就存放在node_modules\axios\dist中),通过改路由的index.js引入:在index.js加入import VueResource from 'vue-resource'和Vue.use(VueResource)即可

2)网上直接下载axios.min.js文件,通过script src的方式进行文件的引入

2.post请求方式:

1)  this.$http({ method:'POST',  

                        url:'/a/b', //接口路径 data:{'a':'123124'}, //参数 

                        headers: {"X-Requested-With": "XMLHttpRequest"}, 

                        }).then((res) => { if(res.body.code == "0") {
                        this.data= res.body.result;
                    } else {

                        this.warnMessage = "获取班级失败";
                        this.colorMessage = "red"
                    }
                }).catch(err => {
                    this.warnMessage = "访问接口失败";
                    this.colorMessage = "red"
                })

2)this.$http.post('../a/b/c', {}, {
                    header: {},
                    emulateJSON: true
                }).then((res) => {
                    if(res.body.code == "0") {
                        this.data= res.body.result;
                    } else {
                        this.warnMessage = "获取班级失败";
                        this.colorMessage = "red"
                    }
                }).catch(err => {
                    this.warnMessage = "访问接口失败";
                    this.colorMessage = "red"
                })

2.get请求方式同post,直接将上面的post改为get即可

猜你喜欢

转载自www.cnblogs.com/zknublx/p/12554770.html