swiper+vuex+mock實現(xiàn)輪播圖功能
mockjs模擬數(shù)據(jù)
安裝依賴包mockjs
在public文件夾中準備需要的圖片
在src文件夾下創(chuàng)建mock文件夾,創(chuàng)建模擬json文件
[
{
"id": "1",
"imgUrl": "/images/banner1.jpg"
},
{
"id": "2",
"imgUrl": "/images/banner2.jpg"
},
{
"id": "3",
"imgUrl": "/images/banner3.jpg"
},
{
"id": "4",
"imgUrl": "/images/banner4.jpg"
}
]
創(chuàng)建sever.js文件,通過Mock.mock方法模擬出數(shù)據(jù)
//先引入mockjs模塊
import Mock from 'mockjs';
//把JSON數(shù)據(jù)格式引入進來[JSON數(shù)據(jù)格式根本沒有對外暴露,但是可以引入]
//webpack默認對外暴露的:圖片、JSON數(shù)據(jù)格式
import banner from './banner.json';
//mock數(shù)據(jù):第一個參數(shù)請求地址 第二個參數(shù):請求數(shù)據(jù)
Mock.mock("/mock/banner",{code:200,data:banner});//模擬首頁大的輪播圖的數(shù)據(jù)
在入口文件引入serve文件
//引入MockServer.js----mock數(shù)據(jù)
import "@/mock/mockServe";
獲取banner輪播圖數(shù)據(jù)
在api文件夾下引入axios發(fā)請求expor const reqGetBannerList=()=>axios.get('/mock/banner')
搭建vuex倉庫
引入ajax請求import { reqGetBannerList } from "@/api"
actions業(yè)務邏輯將data和服務器返回數(shù)據(jù)交給mutations,mutations把服務器返回數(shù)據(jù)賦值給data,定義一個data空數(shù)組存放服務器返回數(shù)據(jù)。
import { reqGetBannerList } from "@/api"
//state倉庫存儲數(shù)據(jù)的地方
const state={
// 輪播圖數(shù)據(jù)
bannerList:[],
}
//actions書寫業(yè)務邏輯
const actions = {
},
async getBannerList({ commit }){
let result =await reqGetBannerList();
if(result.status==200){
commit("GETBANNERLIST", result.data);
}
}
}
//mutations修改state
const mutations={
GETBANNERLIST(state, bannerList) {
state.bannerList = bannerList;
},
}
//getters計算屬性,簡化倉庫數(shù)據(jù)讓組件獲得數(shù)據(jù)更方便
const getters={
}
export default {
state,
mutations,
actions,
getters,
};
搭建carousel輪播圖組件
引入swiper和其樣式,書寫框架和邏輯
<template>
<div class="swiper-container" ref="cur">
<div class="swiper-wrapper">
<div
class="swiper-slide"
v-for="(carousel, index) in list"
:key="carousel.id"
>
<img :src="carousel.imgUrl" />
</div>
</div>
<!-- 如果需要分頁器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要導航按鈕 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
</template>
<script>
//引入Swiper
import Swiper from "swiper";
export default {
name: "Carsousel",
props: ["list"],
watch: {
list: {
//立即監(jiān)聽:不管你數(shù)據(jù)有沒有變化,我上來立即監(jiān)聽一次
//為什么watch監(jiān)聽不大list:因為這個數(shù)據(jù)從來沒有發(fā)生變化(數(shù)據(jù)是父親給的,父親給的時候就是一個對象,對象里面該有的數(shù)據(jù)都是有的)
immediate: true,
handler() {
//只能監(jiān)聽到數(shù)據(jù)已經(jīng)有了,但是v-for動態(tài)渲染結(jié)構(gòu)我們還是沒有辦法確定的,因此還是需要用nextTick
this.$nextTick(() => {
var mySwiper = new Swiper(this.$refs.cur, {
loop: true,
// 如果需要分頁器
pagination: {
el: ".swiper-pagination",
//點擊小球的時候也切換圖片
clickable: true,
},
// 如果需要前進后退按鈕
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
});
});
},
},
},
};
</script>
在入口文件引入import Carsousel from "@/components/Carousel";在父組件組件掛載完畢后調(diào)用dispatch發(fā)送請求,在computed實例用mapState方法拿到輪播圖數(shù)據(jù),調(diào)用porps把屬性綁定傳入組件內(nèi)
Swiper7的默認容器是'.swiper',Swiper6之前是'.swiper-container'