基本使用
首先要安装axios
npm install axios
1 axios的基本语法
vue框架下,使用axios发送get请求
<template>
<div class="left-container">
<h1>Left</h1>
<button @click="getInfo">发起get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async getInfo() {
const { data: res } = await axios.get('http://www.liulongbin.top:3006/api/get')
console.log(res)
},
},
}
</script>
vue框架下,使用axios发送post请求
<template>
<div class="right-container">
<h1>Right</h1>
<button @click="postInfo">发起post请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async postInfo() {
const { data: res } = await axios.post('http://www.liulongbin.top:3006/api/post', { name: 'zs', age: '20' })
console.log(res)
},
},
}
</script>
问题如下:
每次使用axios的时候都需要在当前vue文件中导入使用
2 axios进阶用法1
把axios挂载到Vue的原型上并配置请求根路径。
把axios挂载到Vue的原型上
每一个.vue都是Vue的一个实例
在main.js中增加代码如下
//main.js
import axios from 'axios'
Vue.prototype.axios = axios
// 今后,在每个.vue组件中发起请求,直接调用this.axios.get this.axios.xxx
// 通常命名如下
Vue.prototype.$http = axios
// 今后,在每个.vue组件中发起请求,直接调用this.$http.get this.$http.xxx
则发送get请求可改为this.axios.get
<template>
<div class="left-container">
<h1>Left</h1>
<button @click="getInfo">发起get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async getInfo() {
const { data: res } = await this.axios.get('http://www.liulongbin.top:3006/api/get')
console.log(res)
},
},
}
</script>
则发送post请求可改为this.axios.post
<template>
<div class="right-container">
<h1>Right</h1>
<button @click="postInfo">发起post请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async postInfo() {
const { data: res } = await this.axios.post('http://www.liulongbin.top:3006/api/post', { name: 'zs', age: '20' })
console.log(res)
},
},
}
</script>
配置请求根路径
// 全局配置axios的请求根路径
// axios.defaults.baseURL = '请求根路径'// 配置请求根路径
axios.defaults.baseURL = 'http://www.liulongbin.top:3006'
// 把axios挂载到Vue.prototype上,供每个.vue组件的实例直接使用
Vue.prototype.$http = axios
// 今后,在每个.vue组件中发起请求,直接调用this.$http.get this.$http.xxx
则发送get请求的URL可以省略
<template>
<div class="left-container">
<h1>Left</h1>
<button @click="getInfo">发起get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async getInfo() {
const { data: res } = await this.axios.get('/api/get')
console.log(res)
},
},
}
</script>
则发送post请求可改为this.axios.post
<template>
<div class="right-container">
<h1>Right</h1>
<button @click="postInfo">发起post请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async postInfo() {
const { data: res } = await this.axios.post('/api/post', { name: 'zs', age: '20' })
console.log(res)
},
},
}
</script>
直接把axios挂载到Vue原型的缺点
无法实现api接口的复用,在每个.vue组件中,实现同样的功能需要重新写重复的内容