Vue: axios 请求封装及设置默认域名前缀 (for Vue 2.0)

时间:2023-03-08 20:00:53

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 == ){
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 == ){ }else{
this.$message.error(res.message);
}
}, (err) => {
console.log(err)
});