重点:
重点当然是学会使用 Axios 发送 get 和 post 请求啦~~
准备工作
首先,我们安装 Axios:
npm install axios
然后在项目中引入(哪个组件用到 Axios 就在哪个组件引入):
import axios from 'axios'
可是如果所有组件都要使用 Axios,难道我要在所有组件都引入一次吗?
不用,我们只要将 Axios 全局挂载到 Vue 原型上:
Vue.prototype.$http = axios // $http 是随便起的名字,你也可以使用其他名字
使用 Axios 发送 get 请求
向 Vue中文社区 发送请求(API 可以在 官网提供的 API 找到):
getData () {
this.$http.get('https://www.vue-js.com/api/v1/topics')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
因为 Axios 是基于 Promise 的,所以可以使用 then 和 catch 。
在发送请求时,还可以传递参数,参数的传递有两种方式:
第一种:对象
getData () {
this.$http.get('https://www.vue-js.com/api/v1/topics, {
params: {
page: 1, // 页码
limit: 20 // 每页显示的数量
}
}')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
第二种:类似于查询字符串
getData () {
this.$http.get('https://www.vue-js.com/api/v1/topics?page=1&limit=20')
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
推荐使用第一种方式,因为它修改方便,也更直观。
使用 Axios 发送 post 请求
post 传递数据有两种格式:
- form-data 格式,类似于:?page=1&limit=20
- x-www-form-urlencoded 格式,类似于:{page: 1, limit: 20}
在 Axios 中,post 请求的参数必须是 form-data 格式。
postData () {
this.$http.post(url, {
params: {
page: 1,
limit: 20
}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
上面这种写法是不可行的,后台接收到的数据会是 x-www-form-urlencoded 格式。
这里推荐 qs 插件,使用 qs.stringify 方法,将 对象 转变成 字符串,那么后台接收到的就是 form-data 格式。
安装 qs 插件:
npm install qs
引入 qs:
import qs from 'qs'
然后将上面的 postData 方法改成:
postData () {
this.$http.post(url, qs.stringify({
params: {
page: 1,
limit: 20
}
}))
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
END~~