1:安装axios
npm install axios --save
2:准备好数据源 (使用json-server模拟数据 模拟了一个借口bannerlist)
3:改写Home.vue中代码 把静态的改成动态(数据取值)
<template>
<div class="home">
<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
<van-swipe-item v-for="item in bannerList" :key="item.id">
<img :src="item.src">
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import axios from "axios";
export default {
data(){
return {
bannerList:[]
}
},
created(){
axios({
url:"http://192.168.61.174:6789/bannerlist"
}).then(res=>{
console.log(res.data);
this.bannerList = res.data;
})
}
}
</script>
<style scoped>
.my-swipe .van-swipe-item {
color: #fff;
font-size: 20px;
line-height: 150px;
text-align: center;
background-color: #39a9ed;
width: 100%;
height: 190px;
}
.van-swipe-item img{
height: 100%;
width: 100%;
}
</style>
4:浏览效果
5:组件分离 在components中新建一个文件夹home 里面新建一个文件 Swiper.vue里面写入 就是轮播图的结构 样式 和父组件传来的bannerlist
<template>
<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
<van-swipe-item v-for="item in bannerlist" :key="item.id">
<img :src="item.src" />
</van-swipe-item>
</van-swipe>
</template>
<script>
export default {
props:["bannerlist"]
}
</script>
<style scoped>
.my-swipe .van-swipe-item {
color: #fff;
font-size: 20px;
line-height: 150px;
text-align: center;
background-color: #39a9ed;
width: 100%;
height: 190px;
}
.van-swipe-item img {
height: 100%;
width: 100%;
}
</style>
6:在父组件中使用
<template>
<div class="home">
<swiper :bannerlist="bannerList"></swiper>
</div>
</template>
<script>
import axios from "axios";
import swiper from "../components/home/Swiper"
//引入组件 需要注册才能使用
export default {
data(){
return {
bannerList:[]
}
},
components:{
swiper
},
created(){
axios({
url:"http://192.168.61.174:6789/bannerlist"
}).then(res=>{
console.log(res.data);
this.bannerList = res.data;
})
}
}
</script>
7:父传子说明
重新运行页面即可