使用 vuex 获取状态,JS 分割一维数组,遍历渲染首页导航

1、获取数组

导入 mapState

1
import { mapState } from "vuex";

在组件中获取多个状态,在计算属性中用对象扩展运算符给 mapState 的数组赋值

1
2
3
computed: {
...mapState(["address", "categories", "userInfo"]),
}

分发 Actions

在根节点注入 Store

在 main.js 中 导入 store

1
import store from './store/index'

把 store 对象提供给 “store” 选项

1
2
3
4
5
6
7
8
9
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})

在组件中分发 Action

在组件 mounted 生命周期中,使用 this.$store.dispatch (‘xxx’) 分发 action

mounted 生命周期:挂载完成,也就是模板中的 HTML 渲染到 HTML 页面中,mounted 只会执行一次。

1
2
3
4
mounted() {
this.$store.dispatch("getCategories");
this.$store.dispatch("getShops");
},

在 Chrome 浏览器中的 vue-devtools 插件中 vuex 选项查看状态,如下图

categories
categories

categories 中的数组
categories 中的数组

2、JS 将一维数组分割为特定长度的二维数组

首页导航:数据需要是二维数组

每一页最大 8 个元素,总元素 / 8 = 数组个数,把数组 categories 分为特定个数的数组,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
computed: {
...mapState(["address", "categories", "userInfo"]),

// 导航栏滑动页每一页有八个图标
// 根据categories(一维数组)生成二维数组(内部的数组中的元素个数最大为8个)
categoriesArr() {
const { categories } = this;
// 准备一个空的二维数组
const arr = [];
// 二维数组里面的小数组
let minArr = [];
// 遍历categories
categories.forEach(c => {
// 问题:最后剩下的元素不够8,???

// 如果minArr满了,,生成新的空小数组
if (minArr.length === 8) {
minArr = [];
}
// 将小数组保存到大数组去
if (minArr.length === 0) {
arr.push(minArr);
}
// 将当前分类保存到小数组中
minArr.push(c);
});
console.log(arr, minArr);
return arr;
}
}

3、遍历渲染数组

嵌套 v-for 遍历渲染每一个列表 (八个元素),每一个元素 (图片 + 文字)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<nav class="msite_nav">
<div class="swiper-container" v-if="categories.length">
<div class="swiper-wrapper">
<!-- :pagination="true" -->
<div
class="swiper-slide"
v-for="(categories, index) in categoriesArr"
:key="index"
>
<a
href="javascript:"
class="link_to_food"
v-for="(category, index) in categories"
:key="index"
>
<div class="food_container">
<img :src="baseImageUrl + category.image_url" />
</div>
<span>{{ category.title }}</span>
</a>
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
</div>
<!-- <img src="./images/msite_back.svg" alt="back" v-else /> -->
</nav>

4、使用 swiper、better-scroll 滑动组件

安装

swiper 中文官网:点击跳转 swiper 中文官网

安装 swiper 6.6.1 版本

1
npm install swiper --save

安装 better-scroll 2.3.1 版本

1
npm install better-scroll --save

导入

1
2
import Swiper from "swiper";
import BScroll from "better-scroll";

导入 swiper css 库

1
import "swiper/swiper.min.css";

使用

在 watch 侦听器中监听 categories
界面一旦更新,获取到数据,立刻创建 swiper 对象和 BScroll 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
watch: {
categories(value) {
// 界面一旦更新 => 创建Swiper对象
this.$nextTick(() => {
// 一旦完成界面更新, 立即调用(此条语句要写在数据更新之后)
// 创建一个Swiper实例对象, 来实现轮播
new Swiper(".swiper-container", {
loop: true, // 可以循环轮播
// 如果需要分页器
pagination: {
el: ".swiper-pagination"
}
});

new BScroll(".miste-content-wrapper", {
click: true
});
});
}
}

5、效果

效果展示图
效果展示图