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

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

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

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

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]])node

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

開始使用
vue 自己是不支持 ajax 接口请求的,因此咱们须要安装一个接口请求的 npm 包,来使咱们的项目拥有这个功能。
way1.首先在主入口文件main.js中引用ajax

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

Vue.use(VueAxios,axios);

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

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

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

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

  在组件中使用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添加方法api

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 () {/*...*/});
相关文章
相关标签/搜索