Vue 爬坑之路—— 使用 Vuex + axios 發送請求

Vue 本來有一個官方推薦的 ajax 插件 vue-resource,可是自從 Vue 更新到 2.0 以後,官方就再也不更新 vue-resourcephp

目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求,而大型項目都會使用 Vuex 來管理數據,因此這篇博客將結合二者來發送請求vue

 

前言: 
ios

使用 cnpm 安裝 axiosgit

cnpm install axios -S

安裝其餘插件的時候,能夠直接在 main.js 中引入並 Vue.use(),可是 axios 並不能 use,只能每一個須要發送請求的組件中即時引入github

爲了解決這個問題,有兩種開發思路,一是在引入 axios 以後,修改原型鏈,二是結合 Vuex,封裝一個 aciton。具體的實施請往下看~ajax

 

方案一:改寫原型鏈vuex

首先在 main.js 中引入 axiosnpm

import axios from 'axios'

這時候若是在其它的組件中,是沒法使用 axios 命令的。但若是將 axios 改寫爲 Vue 的原型屬性,就能解決這個問題json

Vue.prototype.$ajax = axios

在 main.js 中添加了這兩行代碼以後,就能直接在組件的 methods 中使用 $ajax 命令axios

this.$ajax.post('/api/v1/repair/typelist')
.then(function(res){
       
})
.catch(function(err){
        console.log(err);
});
this.$ajax.get('/api/v1/repair/changes',{
     params: {
          type: this.type
     }
})
.then(function(res){
      console.log(res.data.data)
})
.catch(function(err){
      console.log(err);
});

  這種寫法 get 是沒有問題的,post 會有問題。

post裏面的數據放在params裏面,這樣是有問題的,在使用axios時,要注意到配置選項中包含params和data二者,覺得他們是相同的,實則否則。 
由於params是添加到url的請求字符串中的,用於get請求。
而data是添加到請求體(body)中的, 用於post請求。而後我把params改成了data,後臺仍是接收不到

解決辦法:

1、URLSearchParams

一、在main.js裏 設置配置,修改Content-Type

import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$axios = axios;

二、在組件vue裏

const url ='http://****你的接口****';
var params = new URLSearchParams();
params.append('key1', 'value1');       //你要傳給後臺的參數值 key/value
params.append('key2', 'value2');
params.append('key3', 'value3');
this.$axios({
    method: 'post',
    url:url,
    data:params
}).then((res)=>{
    
});

這樣後臺就收到數據了 請求成功;不過這個方法兼容性很是很差,ie瀏覽器徹底不兼容。

2、使用qs

安裝qs,在 main.js裏引入

import axios from 'axios'
import qs from 'qs';
Vue.prototype.$qs = qs;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$ajax = axios

在vue組件裏面請求方法

var _this = this;
let postData = _this.$qs.stringify({
     mobile      : _this.form.phone,
     code        : _this.form.code
});
_this.$ajax.post('/index.php/api/v1/user/register', postData)
.then(function(res){
}) .catch(function(err){ console.log(err); });

 這種方法傳遞給後臺是是 相似用逗號分隔的字符串形式的。不是Json形式的,若是後臺要求是json形式的

 _this.$ajax.post('/index.php/api/v1/user/login',{
    key: value
}, {
       headers: {
            'Content-Type': 'application/json'
       }
})
.then(function(res){
                   
})
.catch(function(err){
                    console.log(err);
});

 這種解決了以後本地是沒有問題的。可是若是放到線上有時候仍是會出問題。

  放到線上以後post 會出現跨域的問題:

後端PHP代碼裏面已經設置了容許跨域:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods:POST, GET, OPTIONS');

不明白爲何仍是出現跨域?同時這裏須要提醒的是: 若是你要進行身份認證的話,header裏面

Access-Control-Allow-Origin 不能夠設置爲 * ,這個是之前踩過的坑,你能夠填寫爲你容許跨域的ip地址或者域名

 多個地址設置

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';

$allow_origin = array(
    'http://front.feiquanshijie.com',
    'http://www.lzs.cn'
);

if(in_array($origin, $allow_origin)){
    header('Access-Control-Allow-Origin:'.$origin);
}

 

 

方案二:在 Vuex 中封裝

以前的文章中用到過 Vuex 的 mutations,從結果上看,mutations 相似於事件,用於提交 Vuex 中的狀態 state

action 和 mutations 也很相似,主要的區別在於,action 能夠包含異步操做,並且能夠經過 action 來提交 mutations

另外還有一個重要的區別:

mutations 有一個固有參數 state,接收的是 Vuex 中的 state 對象

action 也有一個固有參數 context,可是 context 是 state 的父級,包含  state、getters

 

Vuex 的倉庫是 store.js,將 axios 引入,並在 action 添加新的方法

// store.js
import Vue from 'Vue'
import Vuex from 'vuex'

// 引入 axios
import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 定義狀態
  state: {
    test01: {
      name: 'Wise Wrong'
    },
    test02: {
      tell: '12312345678'
    }
  },
  actions: {
    // 封裝一個 ajax 方法
    saveForm (context) {
      axios({
        method: 'post',
        url: '/user',
        data: context.state.test02
      })
    }
  }
})

export default store

注意:即便已經在 main.js 中引入了 axios,並改寫了原型鏈,也沒法在 store.js 中直接使用 $ajax 命令

 

附錄:配置 axios 

上面封裝的方法中,使用了 axios 的三個配置項,實際上只有 url 是必須的,完整的 api 能夠參考使用說明

爲了方便,axios 還爲每種方法起了別名,好比上面的 saveForm 方法等價於:

axios.post('/user', context.state.test02)

完整的請求還應當包括 .then 和 .catch

.then(function(res){
  console.log(res)
})
.catch(function(err){
  console.log(err)
})

當請求成功時,會執行 .then,不然執行 .catch

這兩個回調函數都有各自獨立的做用域,若是直接在裏面訪問 this,沒法訪問到 Vue 實例

這時只要添加一個 .bind(this) 就能解決這個問題

.then(function(res){
  console.log(this.data)
}.bind(this))
相關文章
相關標籤/搜索