一. 在vue中引入axios
1.安装 axios
与 vue-axios
npm install axios
npm install vue-axios
- 在
main.js
import 刚刚安装的两个工具包
import VueAxios from 'vue-axios'
import axios from 'axios'
Vue.use(VueAxios, axios)
- 下面我们就可以在页面里面使用
axios
了
this.axios.get('http://127.0.0.1/your_url')
.then(res => {
console.log(res)
}).catch( err => {
this.$notify({title: '错误', message: err, type: 'warning'})
return false
})
二. 封装axios
朋友说直接使用this.axios.get/post
太蠢,给我一个例子,我看了看,感觉改起来有点难,就自己尝试封装了一下,下面是具体过程
- 在
src/
文件夹下新建config/common/
文件夹 - 在
common/
文件夹下面新建立一个config.js
文件,代码如下:
const path = require('path')
module.exports = {
baseUrl: 'http://your_api_url_address'
}
- 再在同一目录下新建
index.js
文件,代码如下:
import config from './config'
export function post (url, data) {
var urlPath = config.baseUrl + url
return new Promise((resolve, reject) => {
this.axios.post(urlPath, data)
.then(res => {
resolve(res.data)
}).catch(error => {
var status = error.response.status
switch (status) {
case 404:this.$router.push('not-found')
break
default:this.$router.push('not-found')
break
}
// reject(error.response.status + error.response.statusText)
})
})
}
在
catch
里面我根据返回状态进行了判断然后进行跳转,
你可以根据需求添加其他的返回状态,或者去掉跳转,把reject
的注释打开,
捕捉的错误会发送到调用方法的catch
里面
- 在
src/
下新建http
文件夹,在文件夹下新建一个404页面,在访问路由404的时候使用,内容自定义,我的代码如下:
<template>
<div>
<el-row>
<el-col :span="24">
<div class="grid-content bg-purple-dark">
<h2>404 NOT FOUND</h2>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
name: 'not-found'
}
</script>
<style scoped>
</style>
- 注册需要的路由,我这里只写了一个 404
not-found
路由,其他路由可自行添加
import Vue from 'vue'
import Router from 'vue-router'
import NotFound from '@/config/http/not-found'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/not-found',
component: NotFound,
name: 'not-found'
}
]
})
export default router
- 在
main.js
中引入配置
import { post } from './config/common/index'
Vue.prototype.$post = post
可以在
common
配置里面再写一个get
方法,引入的时候post后面加个get就好
三. 使用
this.$post('/login', this.FD(this.loginForm))
.then(res => {
// 业务代码
})
至此完成。由于本人刚学vue,当中可能存在一些问题,希望各位能提出指正。