提示:本人是新手,大家看看就好!
封装axios,提示信息使用的是Element-UI
1,首先安装axios+VueAxios
//安装axios
npm install axios -S
//安装VueAxios
npm install --save axios vue-axios
//安装Qs
npm install qs --save-dev
//安装Element-UI
npm i element-ui -S
//安装less-load
npm install lessless-loader --save
或者
npm install --save-dev less-loader less
在main.js中引入
import axios from 'axios'
import VueAxiox from 'vue-axios'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.use(VueAxiox,axios)
在webpack.base.conf.js
eg 1: http://www.css88.com/doc/webpack2/loaders/less-loader/
eg 2: https://blog.csdn.net/zhumengzj/article/details/72832671
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
}
//或者
{
test: /\.less$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'less-loader'
]
}
2,封装BaseUrl以及图片的url
在config/dev.env.js和prod.env.js进行封装,dev为开发环境下,prod为打包后的环境
注意:对应的值不仅需要单引号,也需要双引号
NODE_ENV: '"production"',
BASE_URL: '"http://192.168.1.62:8952/"'
dev.env.js
prod.env.js
调取方法:
process.env.BASE_URL
process.env.IMAGE_URL
打包后对应的url会使用prod.env.js
import axios from 'axios'
import Qs from 'qs'
const that = this;
const params = Qs.stringify({
currentPage: that.currentPage,
showCount: that.showCount,
downPaymentStatus: 1
})
axios.post(process.env.BASE_URL+'bigrichman/getBigrichmanList/', params)
.then(function (response) {
that.tableData = response.data.data.list
that.totalData = response.data.data.total
})
.catch(function (error) {
console.log(error)
})
3,封装axios
axios.js
import axios from 'axios'
import qs from 'qs'
import router from '../../router'
import {Loading, Message} from 'element-ui'
let loadinginstace; //load加载
/**
* axios请求拦截器
* @param {object} config axios请求配置对象
* @return {object} 请求成功或失败时返回的配置对象或者promise error对象
* **/
axios.interceptors.request.use(config => {
// 这里的config包含每次请求的内容
//判断localStorage中是否存在api_token
if (localStorage.getItem('api_token')) {
// 存在将api_token写入 request header
config.headers.apiToken = `${localStorage.getItem('api_token')}`;
}
loadinginstace = Loading.service({fullscreen: true}) // 请求打开loading
return config;
}, err => {
Message.error({
message: '退出登陆',
onClose: function () {
//关闭时的回调函数, 参数为被关闭的 message 实例
router.push({name: 'error-404'});
}
})
return Promise.reject(err);
})
/**
* axios 响应拦截器
* @param {object} response 从服务端响应的数据对象或者error对象
* @return {object} 响应成功或失败时返回的响应对象或者promise error对象
**/
axios.interceptors.response.use(response => {
loadinginstace.close(); // 响应成功关闭loading
return response
}, error => {
Message.error({
message: '退出登陆',
onClose: function () {
router.push({name: 'error-404'});
}
})
return Promise.resolve(error.response)
});
/**
* 状态码
*/
function statusCode(response) {
switch (response.status) {
case 401:
Message.error({
message: '未授权,请登录',
onClose: function () {
router.push({name: 'error-404'});
}
})
break
case 403:
Message.error({
message: '拒绝访问',
onClose: function () {
router.push({name: 'error-403'});
}
})
break
case 404:
Message.error({
message: '请求地址出错',
onClose: function () {
router.push({name: 'error-404'});
}
})
break
case 408:
Message.error({
message: '请求超时',
onClose: function () {
router.push({name: 'error-404'});
}
})
break
case 500:
Message.error({
message: '服务器内部错误',
onClose: function () {
router.push({name: 'error-500'});
}
})
break
default:
return response
}
}
/**
* 请求发出后检查返回的状态码,统一捕获正确和错误的状态码,正确就直接返回response,错误就自定义一个返回对象
* @param {object} response 响应对象
* @return {object} 响应正常就返回响应数据否则返回错误信息
**/
function checkStatus(response) {
// 如果http状态码正常,则直接返回数据
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
if (response.data.resultCode == '-1') {
Message.error({
message: '请求出错',
onClose: function () {
router.push({name: 'error-404'});
}
})
} else {
return response
}
}else {
// 异常状态下,把错误信息返回去
return statusCode(response)
// return {
// data:{
// status: 404,
// resultCode:'-1',
// resultMsg:'网络异常',
// }
// }
}
}
/**
* 检查完状态码后需要检查后如果成功了就需要检查后端的状态码处理网络正常时后台语言返回的响应
* @param {object} res 是后台返回的对象或者自定义的网络异常对象,不是http 响应对象
* @return {object} 返回后台传过来的数据对象,包含code,message,data等属性,
*/
function checkCode(res) {
// 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
if (res.data && (res.status !== 200)) {
return statusCode(res)
}
return res
}
// 请求方式的配置
export default {
post(url, data) { // post
return axios({
method: 'post',
baseURL: process.env.BASE_URL,
url,
data: qs.stringify(data),
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
},
get(url, params) { // get
return axios({
method: 'get',
baseURL: process.env.BASE_URL,
url,
params, // get 请求时带的参数
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
}
}
路由拦截器
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import {Message} from 'element-ui'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export const page403 = {
path: '/403',
meta: {
title: '403-权限不足'
},
name: 'error-403',
component: () => import('@/views/error-page/403.vue')
};
export const page404 = {
path: '/404',
name: 'error-404',
meta: {
title: '404-页面不存在'
},
component: () => import('@/views/error-page/404.vue')
};
export const page500 = {
path: '/500',
meta: {
title: '500-服务端错误'
},
name: 'error-500',
component: () => import('@/views/error-page/500.vue')
};
export const pageRouter = [{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},{
path: '/detail',
name: 'detail',
component: () => import('@/components/detail')
}]
export const router = new Router({
routes: [page403, page404, page500, ...pageRouter]
})
export default router;
//路由守卫,路由拦截器
router.beforeEach((to, from, next) => {
if(!to.matched || to.matched.length === 0){
Message.error({
message:'页面不存在',
duration:'2000',
onClose:function () {
next({
replace: true,
name: 'error-404'
});
}
})
}else{
next();
}
})
4,使用
helloWord.vue
<script>
/* eslint-disable indent */
import Axiox from '../views/util/axios'
export default {
name: 'own',
data () {
return {
tableData: [],
currentPage: 1,
showCount: 7,
totalData: 0,
dialogVisible: false
}
},
created () {
this.init()
},
methods: {
init () {
const that = this
const params = {
currentPage: that.currentPage,
showCount: that.showCount,
downPaymentStatus: 1
}
Axiox.post('settleBigrichman/getSettleBigrichmanList/', params)
.then(function (response) {
that.tableData = response.data.data.list
that.totalData = response.data.data.total
})
.catch(function (error) {
console.log(error)
})
},
handleSizeChange (val) {
this.showCount = val
this.init()
},
handleCurrentChange (val) {
this.currentPage = val
this.init()
},
handleClick (row, column, index) {
console.log(row)
console.log(column)
console.log(index)
},
editClick (row, column, index) {
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
center: true
}).then(() => {
this.$message({
type: 'success',
message: '删除成功!'
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
})
})
}
}
}
</script>
本文章只是自己使用,第一次写应该有很多问题。如有错误请指出来,谢谢,大神勿喷
对应文件在码云中