Vuex4(Module)+Typescript的基本使用

 一、Vuex4介绍

vuex 是一个专为 Vue.js 应用程序开发的状态管理模式+库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。vuex包括五大核心概念分别是State、Getter、Mutation、Action、Module。参考官网:vuex官网

二、 Vuex安装

//现在默认是vuex3,所以加上next安装下一个版本
npm install vuex@next

//package.json文件中,查看版本
"dependencies": {
    "vuex": "^4.0.2"
 },

三、Vuex使用

1、创建store对象

vuex4引入了createStore方法,来创建一个store对象。createStore方法接收一个泛型,对state类型进行限定。引入module将store分割,每个module拥有自己的 state、mutation、action、getter,避免store对象臃肿。如下创建一个store对象,并将其分割成app和user两个module。

import { createStore } from 'vuex';

// 对state的类型进行限定
export interface IRootState {
    user: IUserState;
    app: IAppState;
}

//  创建store对象
export const store = createStore<IRootState>({
    modules: {
        app,
        user,
    },
});

2、定义模块

首先vuex4对模块类型定义如下,S是模块中state的类型限定,R是根store中的state的类型限定

export interface Module<S, R> {
     namespaced?: boolean;
     state?: S | (() => S);
     getters?: GetterTree<S, R>;
     actions?: ActionTree<S, R>;
     mutations?: MutationTree<S>;
     modules?: ModuleTree<R>;
}

定义app模块如下

import { Module, ActionTree, GetterTree, MutationTree } from 'vuex';

const data = {};
const mutations: MutationTree<IAppState> = {};
const actions: ActionTree<IAppState, IRootState> = {};
const getters: GetterTree<IAppState, IRootState> = {};
const appModule: Module<IAppState, IRootState> = {
    state: data,
    actions,
    mutations,
    getters,
};
export default appModule;

vuex 4 引入了一个新的 API 用于在组合式 API 中与 store 进行交互。可以在组件的 setup 钩子函数中使用 useStore 组合式函数来检索 store。

import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()
  }
}

3、注册到main.ts中,这样各个组件中就可以使用store对象了。

// main.ts文件中
import { createApp } from 'vue'
import store from '@/store'

const app = createApp(App)

app.use(store)

app.mount('#app')

四、总结

vuex4的改动相对来说不是很大,除了创建和获取有些区别,使用和以前还是一模一样的。需要注意的是辅助函数那一块,它是不能在组合式写法setup中使用的。也可参考相关文章:vuex4的基本使用(typescript)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 token 的方法,可以参考下面的代码实现: 在 `src/store` 目录下新建 `auth` 目录,用于存放认证相关的代码。 ```typescript // src/store/auth/state.ts export interface AuthState { token: string | null; } export const state: AuthState = { token: localStorage.getItem('token') || null, }; ``` ```typescript // src/store/auth/mutations.ts import { AuthState } from './state'; export const mutations = { setToken(state: AuthState, token: string) { state.token = token; localStorage.setItem('token', token); }, clearToken(state: AuthState) { state.token = null; localStorage.removeItem('token'); }, }; ``` ```typescript // src/store/auth/actions.ts import { ActionContext } from 'vuex'; import { AuthState } from './state'; import { RootState } from '../root-state'; export const actions = { async login(context: ActionContext<AuthState, RootState>, payload: { username: string; password: string }) { // 发送登录请求 const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); if (response.ok) { const { token } = await response.json(); context.commit('setToken', token); } else { throw new Error('登录失败'); } }, logout(context: ActionContext<AuthState, RootState>) { context.commit('clearToken'); }, }; ``` ```typescript // src/store/auth/index.ts import { Module } from 'vuex'; import { AuthState, state } from './state'; import { mutations } from './mutations'; import { actions } from './actions'; import { RootState } from '../root-state'; export const auth: Module<AuthState, RootState> = { namespaced: true, state, mutations, actions, }; ``` 然后,在 `src/store` 目录下新建 `index.ts` 文件,用于创建 store 实例。 ```typescript // src/store/index.ts import { createStore } from 'vuex'; import { auth } from './auth'; import { RootState } from './root-state'; export const store = createStore<RootState>({ modules: { auth, }, }); ``` 最后,在 `main.ts` 中引入 store 实例,并在根组件中注入。 ```typescript // main.ts import { createApp } from 'vue'; import App from './App.vue'; import { store } from './store'; const app = createApp(App); app.use(store); app.mount('#app'); ``` 这样,就可以在组件中通过 `this.$store.state.auth.token` 访问 token 了。在登录成功后,通过 `this.$store.dispatch('auth/login', { username, password })` 更新 token;在注销时,通过 `this.$store.dispatch('auth/logout')` 清除 token。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值