vue中axios请求本地json以及轮播图不loop问题

简单方法

vue-cli4 vue2.6

在 public 目录下创建 data 文件夹,在 data 文件夹中创建 index.json 文件,访问 http://localhost:8080/data/index.json 即可查看到 json 数据。

使用 axios 进行请求的关键代码如下:

1
2
3
4
5
6
7
8
9
10
axios.get('/data/index.json')
.then((res) => {
res = res.data
this.city = res.city
if (res.ret) {
const data = res.data
this.swiperList = data.swiperList
this.iconList = data.iconList
}
})

图片展示:

效果

借助 vue.config.js 配置

借助下面的配置,访问 http://localhost:8080/api/seller 即可查看到 json 数据。

vue.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const appData = require('./data.json')
const seller = appData.seller

module.exports = {
devServer: {
before(app) {
app.get('/api/seller', function (req, res) {
res.json({
errno: 0,
data: seller
})
})
}
}
}

使用 axios 进行请求的关键代码如下:

1
2
3
4
axios.get('/api/seller')
.then((res) => {
console.log(res)
})

页面渲染问题

因为在一开始,轮播图的数组为空,当请求到的时候数组才有数据,这时候就有一个 bug:图片不能循环轮播。解决的方法是加上 v-if

1
2
3
4
5
6
7
8
<swiper :options="swiperOption" v-if="swiperList.length">
<!-- slides -->
<swiper-slide v-for="item in swiperList" :key="item.id">
<img class="img-swiper" :src="item.imgUrl">
</swiper-slide>
<!-- Optional controls -->
<div class="swiper-pagination" slot="pagination"></div>
</swiper>

参考

https://www.imooc.com/article/291839

https://webpack.js.org/configuration/dev-server/#devserverbefore