通过定义的categorysArr二维数组来遍历以及data中定义的baseImageUrl路径
<nav class="msite_nav">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(items,index) in categorysArr" :key="index">
<a href="javascript:" class="link_to_food" v-for="(item,index) in items" :key="index">
<div class="food_container">
<img :src="baseImageUrl+item.image_url">
</div>
<span>{{item.title}}</span>
</a>
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
</div>
</nav>
使用watch/监视categorys变化数据时,this.$nextTick()方法【一旦完成界面更新, 立即调用(此条语句要写在数据更新之后)】
<script>
import { mapState, mapActions } from "vuex";
import HeaderTop from "@/components/HeaderTop/HeaderTop"; //引入头部组件
import ShopList from "@/components/ShopList/ShopList"; //引入首页的商品列表组件
import Swiper from "swiper"; //引入swiper轮播插件
import "swiper/dist/css/swiper.min.css"; //引入swiper样式
export default {
data() {
return {
baseImageUrl: "https://fuss10.elemecdn.com"
};
},
mounted() {
this.getCategorys(); //获取数据
},
methods: {
...mapActions(["getCategorys"])
},
computed: {
//计算属性
//读数据
...mapState(["address", "categorys"]), //如果在之前使用mapActions那么就用mapstate从state.js直接调用属性
//根据categorys一维数组生成一个2维数组 小数组中的元素个数8个
categorysArr() {
const categorys = this.categorys;
const arr = []; //准备空的2维数组
let minArr = []; //准备一个小数组(最大长度为8)
//遍历categorys
categorys.forEach(el => {
//如果当前小数组已经满了,则重新创建一个新的
if (minArr.length === 8) {
minArr = [];
}
//如果minArr是空的,将小数组保存到大数组中
if (minArr.length === 0) {
arr.push(minArr);
}
//将当前分类保存到小数组中
minArr.push(el);
});
return arr;
}
},
//监视
watch: {
//监视categorys变化数据时
categorys(value) {
this.$nextTick(() => {//一旦完成界面更新, 立即调用(此条语句要写在数据更新之后)
界面更新就立即创建swiper对象,swiper对象来实现轮播
new Swiper(".swiper-container", {
loop: true, //可以循环轮播
pagination: {
el: ".swiper-pagination"
}
});
});
}
},
components: {
HeaderTop,
ShopList
}
};
</script>