当前位置: 首页 > news >正文

vue2.0中ts中vuex模块化如何使用

vue2.0中ts中vuex模块化如何使用

  • 一、store中如何配置
    • 1.index.ts
    • 2.user.ts
  • 二、如何使用vuex

一、store中如何配置

1.index.ts

import Vue from 'vue';
import Vuex from 'vuex';
import { UserStateType } from './modules/user'; //导入 UserStateType 类型
Vue.use(Vuex);export interface IRootState {user: UserStateType;
}//创建并导出一个新的 Vuex Store 实例,该实例接受一个泛型参数 IRootState
export default new Vuex.Store<IRootState>({});

2.user.ts


import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators';
import store from '@/store';// 定义了一个接口 UserStateType,包含了用户状态的属性和类型信息
export interface UserStateType {token: string;rootGroupId: number;
}// dynamic: true:指定模块为动态加载。
// namespaced指定模块的命名空间为 true。启用命名空间后,模块的 actions、mutations 和 getters 将自动命名空间处理。
@Module({ dynamic: true, store, namespaced: true, name: 'user' })// class User:定义了一个名为 User 的类。
// extends VuexModule:让 User 类继承自 Vuex 模块的基类 VuexModule,这是 Vuex 模块的基本要求。
// implements UserStateType:表明该类实现了 UserStateType 接口,即遵循了 UserStateType 接口所定义的属性和类型。
class user extends VuexModule implements UserStateType {// tokenpublic token = '';public rootGroupId = 0; // 根节点id//存入token@Mutationpublic SET_TOKEN(token: string) {this.token = token;}//对外暴露存入token@Actionpublic setToken(token: string) {this.SET_TOKEN(token);}//   获取用户的token@Actionpublic getToken() {return this.token;}get getRootGroupId() {return this.rootGroupId;}// 根节点id@MutationSET_ROOT_GROUP_ID(params: number): void {this.rootGroupId = params;}@ActionsetRootGroupId(params: number): void {this.context.commit('SET_ROOT_GROUP_ID', params);}
}// 导出 UserModule 的模块实例
export const UserModule = getModule(user);

二、如何使用vuex

import { UserModule } from '../store/modules/user';// 用于设置UserModule 模块中的 rootGroupId 属性值。
UserModule.setRootGroupId(8);// 用于获取 UserModule 模块中的 rootGroupId 属性值。
get sidebar() {return UserModule.rootGroupId;
}

http://www.mrgr.cn/news/18095.html

相关文章:

  • 完美解决LBP2900打印机安装驱动提示无法识别USB及连接错误等问题(附Win11全新安装支持及卸载方案)
  • 【GeoSceneWebAdaptor】
  • Cobalt Strike 4.8 用户指南-第五节-获取初始访问
  • Java 技术教程:@JsonInclude(JsonInclude.Include.NON_EMPTY) 注解详解
  • 情感分析——中文金融情感词典
  • CommonJS与ESModule标准
  • redisson RMap和RMapCache的区别
  • 2024年,人工智能行业哪些证书权威?
  • 【微信小程序入门】2、微信小程序开发前准备
  • echarts处理y轴最大小值根据数据动态处理、分割数和是否从0开始
  • Java学习第六天
  • 用相图分析 bbr,inflight 守恒的收敛速度
  • 世界上最快的端口扫描器masscan,如何使用?如何进行分布式使用部署?如何集成到web系统?
  • 【前端 · 面试 】HTTP 总结(九)—— HTTP 协商缓存
  • 2025毕业季:如何用Java SpringBoot构建医疗就诊平台?掌握最新技术,开启医疗信息化大门
  • 盲盒小程序开发,探索市场发展优势
  • 多看书,一年顶十年!(码农必读书单)
  • 多目标应用:基于自组织分群的多目标粒子群优化算法(SS-MOPSO)的移动机器人路径规划研究(提供MATLAB代码)
  • PANDA:免微调提升大模型领域特定能力的新方法
  • C语言典型例题59