1. 程式人生 > >Vue: axios 請求封裝及設置默認域名前綴 (for Vue 2.0)

Vue: axios 請求封裝及設置默認域名前綴 (for Vue 2.0)

找到 檢查 evel require login word -- const 步驟

1. 實現效果

以get方法向http://192.168.32.12:8080/users 發起請求、獲取數據並進行處理

this.apiGet(/users, {})
  .then((res) => {
    console.log(res)
  }, (err) => {
    console.log(err)
  })

2. 實現步驟一之配置域名前綴

2.1 安裝axios

cnpm install axios --save

2.2 配置webpack.base.conf.js 文件

引入

const webpack = require(webpack)

在項目根目錄下的build 中可以找到webpack.base.conf.js 文件,對文件中的內容進行以下兩項操作:

  在module.exports之前插入代碼

// define the different HOST between development and production environment
var DEV_HOST = JSON.stringify(http://192.168.32.12:8080)
var PUB_HOST = JSON.stringify(http://{部署服務器ip和端口})

  在module.exports 中添加與entry、output、resolve等選項並列的plutins選項

plugins: [
  new webpack.DefinePlugin({
    HOST: process.env.NODE_ENV 
=== production ? PUB_HOST : DEV_HOST })

2.3 配置main.js 文件

import axios from axios
axios.defaults.baseURL = HOST
window.axios = axios
window.HOST = HOST
 
const bus = new Vue()
window.bus = bus

3. 實現步驟二之封裝axios

3.1 新建http.js 文件, static下邊新建 js 文件夾

const apiMethods = {
    methods: {
        apiGet(url, data) {
            
return new Promise((resolve, reject) => { axios.get(url, data).then((response) => { resolve(response.data) }, (response) => { reject(response) console.log(response) bus.$message({ message: 請求超時,請檢查網絡, type: warning }) }) }) }, apiPost(url, data) { return new Promise((resolve, reject) => { axios.post(url, data, { headers: { Content-Type: application/json } }).then((response) => { resolve(response.data) }).catch((response) => { console.log(f, response) resolve(response) bus.$message({ message: 請求超時,請檢查網絡, type: warning }) }) }) } } } export default apiMethods

3.2 文件引入

在需要發送ajax的請求文件中引入http.js

import http from ../../../../static/js/http.js

並在該文件的export default 末尾添加選項

mixins: [http]

3.3 方法調用

this.apiGet(/index.php/api/v1/goods/list, {
                    params: {
                        property_name: 秒殺
                    }
                })
                .then((res) => {
                    if(res.code == 0){
                        this.hotListDate = res.result;
                    }else{
                        this.$message.error(res.message);
                    }
                }, (err) => {
                    console.log(err)
                });

post

this.apiPost(/index.php/api/v1/user/login, {
                    mobile      : this.form.phone,
                    password    : this.form.password
                })
                .then((res) => {
                    if(res.code == 0){
                       
                    }else{
                        this.$message.error(res.message);
                    }
                }, (err) => {
                    console.log(err)
                });

Vue: axios 請求封裝及設置默認域名前綴 (for Vue 2.0)