uniapp自定义底部tabbar 中this.$store
时间: 2025-05-24 11:01:06 浏览: 17
### 实现 UniApp 自定义底部 TabBar 的 Vuex 状态管理
在 UniApp 中实现自定义底部 TabBar 并通过 Vuex 进行状态管理时,可以按照以下方式构建代码结构和逻辑。
#### 1. 定义 Vuex Store
首先,在 `store` 文件夹下创建一个模块化的 Vuex 存储文件。以下是基于引用的内容以及最佳实践的配置:
```javascript
// store/modules/tabBar.js
export default {
state: {
tabBarList: [
{ pagePath: "/pages/home/home", text: "首页", iconPath: "home.png", selectedIconPath: "home-active.png" },
{ pagePath: "/pages/cart/cart", text: "购物车", iconPath: "cart.png", selectedIconPath: "cart-active.png" },
{ pagePath: "/pages/user/user", text: "我的", iconPath: "user.png", selectedIconPath: "user-active.png" }
],
tabbarIndex: 0,
isMemberType: false // 假设用于判断会员类型的布尔值
},
getters: {
tabBarList: (state) => state.tabBarList, // 获取 TabBar 列表数据[^2]
currentTabIndex: (state) => state.tabbarIndex, // 当前选中的 TabBar 索引[^3]
isMemberType: (state) => state.isMemberType // 是否为会员类型[^1]
},
mutations: {
updateTabBarList(state, newList) {
state.tabBarList = newList;
},
setTabIndex(state, index) {
state.tabbarIndex = index; // 更新当前选中的 TabBar 索引[^3]
},
toggleMemberType(state, value) {
state.isMemberType = value; // 修改会员类型标志位
}
},
actions: {
changeTabIndex({ commit }, newIndex) {
commit('setTabIndex', newIndex);
}
}
};
```
#### 2. 页面中引入并绑定 Vuex 数据
在需要显示 TabBar 的页面中,可以通过 `computed` 属性来获取 Vuex 中的数据,并将其传递给组件。
```html
<template>
<div class="container">
<!-- u-tabbar 是 uni-app 提供的一个 UI 库组件 -->
<u-tabbar :list="tabbar" :current="currentIndex" @change="handleTabChange" active-color="#EB3477"></u-tabbar>
</div>
</template>
<script>
import { mapState, mapGetters } from 'vuex';
export default {
computed: {
...mapState({
currentIndex: (state) => state.tabbarIndex, // 映射当前索引到计算属性
tabbar: (state) => state.tabBarList // 映射 TabBar 列表到计算属性
}),
...mapGetters(['isMemberType']) // 如果需要用到 getter 方法也可以这样映射
},
methods: {
handleTabChange(index) {
this.$store.dispatch('changeTabIndex', index); // 调用 Vuex action 来改变当前索引[^3]
}
}
};
</script>
<style lang="scss" scoped>
@import "uview-ui/index.scss";
.container {
display: flex;
flex-direction: column;
}
</style>
```
#### 3. 解决动态高亮问题
为了确保点击后 TabBar 图标的高亮效果正常工作,需在 Vuex 中维护当前激活的 TabBar 索引,并同步至组件的状态中。这一步骤非常重要,因为如果未正确设置索引,则可能导致界面无法及时响应用户的交互操作[^3]。
#### 4. 关于单一职责原则的应用
Vuex 的设计遵循了 **单一职责原则**,即每个模块只负责特定的功能范围内的状态管理和变更处理。例如,这里的 `tabBar` 模块仅专注于管理与 TabBar 相关的状态(如列表项、当前索引等),而不会涉及其他无关功能的状态存储或修改[^4]。
---
###
阅读全文
相关推荐


















