vue2的Ajax二次封装

vue.js        Ajax(vue-resource)

vue要实现异步加载需要使用到vue-resource库,而在vue.js 2.0版本推荐使用axios来完成ajax请求

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

Get请求

window.onload = function(){
    var vm = new Vue({
        el:'#box',
        data:{
            msg:'Hello World!',
        },
        methods:{
            get:function(){
                //发送get请求
                this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
                    document.write(res.body);    
                },function(){
                    console.log('请求失败处理');
                });
            }
        }
    });
}

post请求

post发送到数据到后端,需要第三个参数{ emulateJSON : ture }

emulateJSON的作用:如果web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项

window.onload = function(){
    var vm = new Vue({
        el:'#box',
        data:{
            msg:'Hello World!',
        },
        methods:{
            post:function(){
                //发送 post 请求
                this.$http.post('/try/ajax/demo_test_post.php',{name:"菜鸟教程",url:"http://www.runoob.com"},{emulateJSON:true}).then(function(res){
                    document.write(res.body);    
                },function(res){
                    console.log(res.status);
                });
            }
        }
    });
}

demo_test_post.php代码如下:

<?php
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$city = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo '网站名: ' . $name;
echo "\n";
echo 'URL 地址: ' .$city;
?>

你也可以使用全局对象方式Vue.http或者在一个Vue实例的内部使用this.$http来发起请求

// 基于全局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);

一.axios的二次封装

ajax的二次封装的目的是:方便统一管理        下载:npm i axios

1.配置拦截器

在 src 目录下新建 utils 文件夹,该文件夹下创建 request.js 文件

request.js文件

        1.首先创建axios对象

        2.添加请求拦截器(前端给后端的参数)

        3.添加响应拦截器(后端给前端的数据)

import axios from 'axios'

// 创建 axios 对象
const instance = axios.create({
    baseURL: 'http://testapi.xuexiluxian.cn/api', // 根路径
    timeout: 2000 // 网络延时
})

// 添加请求拦截器 => 前端给后端的参数【还没到后端响应】
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器 => 后端给前端的数据【后端返回给前端的东西】
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

// 最终返回的对象
export default instance

2.配置拦截器

在需要发请求的组件中,导入request.js,之后发送请求即可

App.vue 组件

        1.在需要使用的组件中导入 request

        2.直接发送即可

<template>
  <div id="app">前端杂货铺</div>
</template>

<script>
import request from "./utils/request";
export default {
  name: "App",
  data() {
    return {};
  },
  created() {
  	// get 请求
    request({
      url: "/course/category/getSecondCategorys",
    }).then((res) => {
      console.log(res);
    });

	// post 请求
    request({
      url: "/course/mostNew",
      method: "post",
      data: {
        pageNum: 1,
        pageSize: 5,
      },
    }).then((res) => {
      console.log(res);
    });
  }
}
</script>

 文件结构如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值