vue请求封装,Store-状态管理部分(文档笔记)

    科技2025-12-30  9

    Store-状态管理

    目录结构

    . ├── src 源码目录 │ ├── store 状态管理配置 │ │ ├── module 模块状态管理,登录、产品等分别模块; │ │ │ ├── authority ├── index.js authority模块的存储,不拆分文件的存储方式 │ │ │ ├── xxx 存储xxx模块state(命名和view下的模块文件夹保持一致) ├── actions.js 处理数据动作,处理需要存储的数据后再进行派发mutations, action 重点在内部执行异步操作 ├── getters.js 获取过滤数据,获取数据 ├── index.js 配置xxx模块入口文件 ├── mutation-types.js配置Store中所有状态的mutations ├── mutation.js 更改store中的状态的唯一方法是提交mutation;通过派发,commit改变store存储的数据 ├── state.js 初始的store数据 │ │ ├── index.js 生成vux Store对象配置,聚合modules中各模块的状态 .

    如何新增store?

    例:新增一个department的模块的currentDepartment状态管理

    第一步:新增一个名字为department的store模块

    复制store -> modules -> meetingLayout,重命名为department

    第二步: mutations.js,中新增代码

    复制store -> modules -> department -> mutations.js,中新增代码: import * as types from '../mutation-types' const department = { state: { currentDepartment: null }, mutations: { [types.SET_CURRENT_DEPARTMENT] (state, department) { state.currentDepartment = department }, } } export default department

    第三步:暴露SET_CURRENT_DEPARTMENT方法

    在store-> modules -> department -> mutation-types.js,配置上一步定义的SET_CURRENT_DEPARTMENT方法

    export const SET_USER_INFO = 'SET_USER_INFO' export const SET_CURRENT_DEPARTMENT = 'SET_CURRENT_DEPARTMENT'

    第四步:将department模块聚合到store中

    修改store->index.js文件

    导入department模块 import app from './modules/app' import department from './module/department' 将department加入到store的modules中 modules: { app, department }

    如何使用store中新增的currentDepartment

    获取、修改currentDepartment

    在vue文件中导入mapState,mapMutations

    import { mapState, mapMutations } from 'vuex'
    获取
    在vue的computed中,聚合需要引入的模块 computed: { ...mapState(['department']), //or ...mapState('department', { currentDepartment: state => state.currentDepartment }), },

    综上,就可以在vue中通过this.department.currentDepartment使用currentDepartment这个状态了

    在template中使用 department.currentDepartment 在vue script中 this.department.currentDepartment
    修改
    在vue的methods中,引入SET_CURRENT_DEPARTMENT方法 methods: { ...mapMutations(['SET_CURRENT_DEPARTMENT']), ...mapMutations([ 'increment', // script中通过 `this.increment()` 映射为 `this.$store.commit('increment')` // `mapMutations` 也支持载荷: 'incrementBy' // script中通过 `this.incrementBy(amount)` 映射为`this.$store.commit('incrementBy', amount)` ]), } 在vue的script中,修改current_department this.SET_CURRENT_DEPARTMENT(department); // 映射为 `this.$store.commit('SET_CURRENT_DEPARTMENT', department)`
    使用Actions
    import { mapActions } from 'vuex' methods: { ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) }
    Processed: 0.013, SQL: 9