axios的基本样式
methods: {
// 封装请求列表数据的方法
async initCartList() {
// 调用 axios 的 get 方法,请求列表数据
const { data: res } = await axios.get('https://www.escook.cn/api/cart')
// 只要请求回来的数据,在页面渲染期间要用到,则必须转存到 data 中
if (res.status === 200) {
this.list = res.list
}
},
}
created() {
// 调用请求数据的方法
this.initCartList()
}
二:
import axios from 'axios'
const base = {
baseUrl: 'http://api.tianapi.com',
ncov: '/ncov/index',
city: 'https://interface.sina.cn/news/wap/fymap2020_data.d.json'
}
const api = {
getNcov (params) {
return axios.get(base.baseUrl + base.ncov, {
params
})
}
}
export default api
import api from '../api/index'
created () {
api.getNcov({ key: '4818c9f414cad9077e442646480db943' }).then(res => {
console.log(res.data.newslist[0].desc)
if (res.data.code === 200) {
}}).catch(err => {})
导出去的api方法代表整个../api/index文件
url的query路径参数是用{ }包裹的
三:完整的axios调用
使用多个axios的时候,使用axios.create()最为快捷
-
首先在目录下创建utils下的index.js
-
import axios from 'axios' const request = axios.create({ // 请求地址的根目录 baseURL: 'https://www.escook.cn' }) export default request
-
在article.js之中创建模块
// // 文章相关的 API 接口,都封装到这个模块中 import request from '@/utils/request.js' export const getArticleListAPI = function(_page, _limit) { return request.get('/articles', { params: { _page: _page, _limit: _limit } }) }
-
在组件中
import { getArticleListAPI } from '@/api/articleAPI.js' <script> data() { return { artlist: [] } }, created() { this.initArticleList() }, methods: { async initArticleList() { const { data: res } = await getArticleListAPI(1, 6) console.log(res) this.artlist = res } </script> axios.create(baseURL: ).get()
之后在data(){ return{artlist:[]}},用数组接收数据,把数据存起来
## 源代码
下面有源代码:
```JavaScript
// 1.创建xhr对象
let xhr = new XMLHttpRequest();
// 2.调用open()
// ?问号后面是参数,
// 这里的参数是直接加到url后面
// http://www.liulongbin.top:3006/api/getbooks?id=1&name=lqc
// 在$.get()中的[data]就是把里面的数据填到xmlhttprequest的url的后面,两者是相连通的
// 就连vue的axios也是这个道理,用{id:1}的键值对传递参数,最后拼接到url之中
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
xhr.send()
xhr.onreadystatechange = function () {
// readyState为0的时候,let xhr = new XMLHttpRequest();创建完成
// readyState为1的时候,open()已经被调用了
// readyState为2的时候,send()调用
// readyState为3的时候,表示完成部分请求
// readyState表示请求完成,表示数据传输完成或者失败(所以需要辅助status的值,判断他是成功还是失败)
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取请求的数据
console.log(xhr.responseText);
}
}
```