vue axios----基于 Promise 的 HTTP 请求

vue axios
vue2.0之axios接口請求管理
功能特性
axios API
開始使用
get請求
post请求
多个请求并发
拦截器
移除一个拦截器:
自定义的 axios 实例添加拦截器:
vue2.0之axios接口請求管理
基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,尤雨溪宣布停止更新vue-resource,并推荐大家使用axios之后,越来越多的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目会使用 Vuex 来管理数据

功能特性
1.在浏览器中发送 XMLHttpRequests 请求
2.在 node.js 中发送 http请求
3.支持 Promise API
4.拦截请求和响应
5.转换请求和响应数据
6.自动转换 JSON 数据
7.客户端支持保护安全免受 XSRF 攻击

axios API
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

注意
当使用别名方法时, url、 method 和 data 属性不需要在 config 参数里面指定。

開始使用
vue 本身是不支持 ajax 接口请求的,所以我们需要安装一个接口请求的 npm 包,来使我们的项目拥有这个功能。
way1.首先在主入口文件main.js中引用

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

  在组件文件中的methods里去使用

this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })

  way2.axios 改写为 Vue 的原型属性
首先在主入口文件main.js中引用,之后挂在vue的原型链上

import axios from 'axios'
Vue.prototype.$ajax= axios

  在组件中使用

this.$ajax.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })

  way3.结合 Vuex的action ,在vuex的仓库文件store.js中引用,使用action添加方法

import Vue from 'Vue'
import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
  // 定义状态
  state: {
    user: {
      name: 'xiaoming'
    }
  },
  actions: {
    // 封装一个 ajax 方法
    login (context) {
      axios({
        method: 'post',
        url: '/user',
        data: context.state.user
      })
    }
  }
})

export default store

在组件中发送请求的时候,需要使用 this.$store.dispatch

methods: {
  submitForm () {
    this.$store.dispatch('login')
  }
}

  

get請求

写法如下:

axios.get('/detail?id=10').then(function (res) {
    //成功获取数据
   console.log(res);
 }).catch(function (err) {
    //请求错误
   console.log(err);
 });

  

get请求也可以通过 params 对象传递参数。写法如下:

 axios.get('/detail', {
    //参数
   params: {
        id: 10
    }
 }).then(function (res) {
    //成功获取数据
    console.log(res);
 }).catch(function (err) {
    //请求错误
    console.log(err);
 });

  

post请求

写法如下:

/执行post请求
 axios.post('/add', {
    name: 'haqiu',
    age: 26
 }).then(function (res) {
    //请求成功
  console.log(res);
 }).catch(function (err) {
    //请求失败
  console.log(err);
 });

  

多个请求并发

除了最常用的get请求和post请求以外,值得一提的是axios提供了一次性并发多个请求的API,使用方法如下:

function getProfile(){
    //请求1
    return axios.get('/profile');
 }
 function getUser(){
    //请求2
    return axios.get('/user');
 }
 //并发请求
 axios.all([
    getProfile(),
    getUser()
 ]).then(axios.spread((res1, res2)=>{
    //两个请求现已完成
   console.log(res1);
    console.log(res2);
 }));

  

拦截器

你可以在处理 then 或 catch 之前拦截请求和响应

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
 
// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

  

移除一个拦截器:

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

  

自定义的 axios 实例添加拦截器:

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

  

posted @ 2019-07-04 17:22  不会Coding的王震  阅读(848)  评论(0编辑  收藏  举报