《vue3+ts+element-plus 后台管理系统系列》之vuex4.x

vue3-composition-admin 是一个管理端模板解决方案,它是基于vue3,ts和element-plus,项目都是以composition api风格编写。
 

Vuex4.x 和 TS 一起分包变化也是比较多的,先从官方例子说起。基础例子请查看官网,传送vuex4.x官网

项目基于Composition API ,下面都是默认使用Composition API 。

 

vuex4.x 不分包


基操:main文件use 一下。

1. 获取store

import { useStore } from 'vuex'

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

2. 访问store state和getter


import { computed } from 'vue'
import { useStore } from 'vuex'

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

    return {
      // access a state in computed function
      count: computed(() => store.state.count),

      // access a getter in computed function
      double: computed(() => store.getters.double)
    }
  }
}

3. 访问store Mutations和Actions

import { useStore } from 'vuex'

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

    return {
      // access a mutation
      increment: () => store.commit('increment'),

      // access an action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}

 

vuex4.x 分包(js基础版)


代码地址:传送门

index.js


import { createStore, createLogger } from 'vuex'
import cart from './modules/cart'
import products from './modules/products'

const debug = process.env.NODE_ENV !== 'production'

export default createStore({
  modules: {
    cart,
    products
  },
  strict: debug,
  plugins: debug ? [createLogger()] : []
})

模块


import shop from '../../api/shop'

// initial state
const state = {
  all: []
}

// getters
const getters = {}

// actions
const actions = {
  getAllProducts ({ commit }) {
    shop.getProducts(products => {
      commit('setProducts', products)
    })
  }
}

// mutations
const mutations = {
  setProducts (state, products) {
    state.all = products
  },

  decrementProductInventory (state, { id }) {
    const product = state.all.find(product => product.id === id)
    product.inventory--
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

 

vuex4.x 分包(ts基础自动引入版)


目录:

在这里插入图片描述

分包的时候我们往往需要手动在index 文件导入分包模块,这样比较麻烦多人开发时候也容易冲突。

利用webpack require 可以自动导入modules 文件,简化操作。

modules > index.ts 代码:


// require.context 适合在同时引用一个目录下多个文件的问题
// require.context函数接受三个参数(路径,是否遍历文件子目录,匹配文件的正则)
// directory {String} -读取文件的路径
// useSubdirectories {Boolean} -是否遍历文件的子目录
// regExp {RegExp} -匹配文件的正则
const files = require.context('.', true, /\.ts$/)
const modules: any = {}
// 遍历取出的file,查找model 给const modules。
files.keys().forEach(key => {
  if (key === './index.ts') return
  const path = key.replace(/(\.\/|\.ts)/g, '')
  const [namespace] = path.split('/')
  // namespace 为modules 下的文件名
  //   if (!modules[namespace]) {
  //     modules[namespace] = {
  //       namespace: true
  //     }
  //   }
  modules[namespace] = { namespaced: true }
  modules[namespace].actions = files(key).default.actions
  modules[namespace].mutations = files(key).default.mutations
  modules[namespace].state = files(key).default.state
  modules[namespace].getters = files(key).default.getters
  console.log(modules)
})

export default modules

index.ts 代码动态加载moudles里面的模块:


import { createStore } from 'vuex'
import modules from './modules'
// 使用VUEx 存储
export default createStore({
  // vuex的基本数据,用来存储变量
  state: { a: 1 },
  // 提交更新数据的方法,必须是同步的(如果需要异步使用action)。
  mutations: {},
  actions: {},
  // 从基本数据(state)派生的数据,相当于state的计算属性
  getters: {},
  // 模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters
  modules: {
    ...modules
  }
})

modules 的模块代码示例:


import { UserModel } from '@/views/global/UserModel'
import { Convert } from '@/utils/jsonToModel'
import storage, { StorageType } from '@/utils/storage'

// import RCStorage from '@/utils/storage'
const actions = {}
// 修改状态
const mutations = {
  // Vuex提供了commit方法来修改状态 使用时 $store.commit('handleUserName',name)
  SET_USER: (state: any, user: UserModel) => {
    state.token = user
    console.log(user)
    // 把登录的用户的名保存到localStorage中,防止页面刷新,导致vuex重新启动,(初始值为空)的情况
    // RCStorage.shared()
    storage.rcSetItem(StorageType.local, 'user', Convert.modelToJson(user))
  }
}
// 定义基本属性
const state = {
  user: '' || storage.rcGetItem(StorageType.local, 'user')
}
// getters 只会依赖 state 中的成员去更新
const getters = {
  // 尖头函数
  USER_GET: (state: any): UserModel => {
    console.log(state.user)
    if (state.user) {
      return Convert.jsonToModel(state.user)
    }
    const tempModel: UserModel = {
      token: '',
      loginType: '',
      loginAccount: '',
      name: '',
      phoneNumber: ''
    }
    return tempModel
  }
}
// 使用VUEx 存储
export default {
  namespaced: true,
  // vuex的基本数据,用来存储变量
  state,
  // 提交更新数据的方法,必须是同步的(如果需要异步使用action)。
  mutations,
  actions,
  // 从基本数据(state)派生的数据,相当于state的计算属性
  getters
}


 

vuex4.x 分包(ts vuex-module-decorators版)


借助 vuex-module-decorators库,将vuex 使用class话,可以优雅避免硬编码。(以上版本使用逃不开硬编码)

代码示例:传送门

index.ts 代码:


import Vue from 'vue'
import Vuex from 'vuex'
import { IAppState } from './modules/app'
import { IUserState } from './modules/user'
import { ITagsViewState } from './modules/tags-view'
import { IErrorLogState } from './modules/error-log'
import { IPermissionState } from './modules/permission'
import { ISettingsState } from './modules/settings'

Vue.use(Vuex)

export interface IRootState {
  app: IAppState
  user: IUserState
  tagsView: ITagsViewState
  errorLog: IErrorLogState
  permission: IPermissionState
  settings: ISettingsState
}

// Declare empty store first, dynamically register all modules later.
export default new Vuex.Store<IRootState>({})


** 以 app.ts 模块代码为例:**


import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import { getSidebarStatus, getSize, setSidebarStatus, setLanguage, setSize } from '@/utils/cookies'
import { getLocale } from '@/lang'
import store from '@/store'

export enum DeviceType {
  Mobile,
  Desktop,
}

export interface IAppState {
  device: DeviceType
  sidebar: {
    opened: boolean
    withoutAnimation: boolean
  }
  language: string
  size: string
}

@Module({ dynamic: true, store, name: 'app' })
class App extends VuexModule implements IAppState {
  public sidebar = {
    opened: getSidebarStatus() !== 'closed',
    withoutAnimation: false
  }

  public device = DeviceType.Desktop
  public language = getLocale()
  public size = getSize() || 'medium'

  @Mutation
  private TOGGLE_SIDEBAR(withoutAnimation: boolean) {
    this.sidebar.opened = !this.sidebar.opened
    this.sidebar.withoutAnimation = withoutAnimation
    if (this.sidebar.opened) {
      setSidebarStatus('opened')
    } else {
      setSidebarStatus('closed')
    }
  }

  @Mutation
  private CLOSE_SIDEBAR(withoutAnimation: boolean) {
    this.sidebar.opened = false
    this.sidebar.withoutAnimation = withoutAnimation
    setSidebarStatus('closed')
  }

  @Mutation
  private TOGGLE_DEVICE(device: DeviceType) {
    this.device = device
  }

  @Mutation
  private SET_LANGUAGE(language: string) {
    this.language = language
    setLanguage(this.language)
  }

  @Mutation
  private SET_SIZE(size: string) {
    this.size = size
    setSize(this.size)
  }

  @Action
  public ToggleSideBar(withoutAnimation: boolean) {
    this.TOGGLE_SIDEBAR(withoutAnimation)
  }

  @Action
  public CloseSideBar(withoutAnimation: boolean) {
    this.CLOSE_SIDEBAR(withoutAnimation)
  }

  @Action
  public ToggleDevice(device: DeviceType) {
    this.TOGGLE_DEVICE(device)
  }

  @Action
  public SetLanguage(language: string) {
    this.SET_LANGUAGE(language)
  }

  @Action
  public SetSize(size: string) {
    this.SET_SIZE(size)
  }
}

export const AppModule = getModule(App)

使用:


import { AppModule, DeviceType } from '@/store/modules/app'

// state
AppModule.device

//actions
AppModule.CloseSideBar(false)

 

vuex4.x 分包(ts 类型推断type版)


这种方式是我比较喜欢,也是项目在用的,文件划分清晰,使用可读性高,类型推断好。

代码 demo地址:传送门

整体目录:

在这里插入图片描述

index.ts代码:

vuex index基操,另外做了分包和类型相关的活。

注意:使用一定要用这里的useStore 函数。


import { createStore, createLogger } from 'vuex'

import {
  AppModule,
  AppStore,
  AppState
} from '@/store/app'
import { AppActionTypes } from '@/store/app/actions'
import { AppMutationTypes } from '@/store/app/mutations'

import {
  AuthModule,
  AuthStore,
  AuthState
} from '@/store/auth'
import { AuthActionTypes } from '@/store/auth/actions'
import { AuthMutationTypes } from '@/store/auth/mutations'

export type RootState = {
  APP: AppState;
  AUTH: AuthState;
}

export const AllActionTypes = {
  APP: AppActionTypes,
  AUTH: AuthActionTypes
}

export const AllMutationTypes = {
  APP: AppMutationTypes,
  AUTH: AuthMutationTypes
}

export type Store =
  AuthStore &
  AppStore

export const store = createStore({
  plugins:
    process.env.NODE_ENV === 'production'
      ? []
      : [createLogger()],
  modules: {
    APP: AppModule,
    AUTH: AuthModule
  }
})

export function useStore (): Store {
  return store as Store
}

export default store

模块代码

目录:

在这里插入图片描述
具体代码不贴了,查看demo。

使用


 setup () {
    const store = useStore()
    const { APP, AUTH } = store.state

    return {
      title: computed(() => AUTH.title),
      loading: computed(() => APP.loading),
      todos: computed(() => APP.todos),
      startGetTodos: () => store.dispatch(AllActionTypes.APP.StartGetTodos, undefined, { root: true })
    }
  }


总结

重点在于让vuex支持type 枚举类型推断


import { ActionContext, CommitOptions, DispatchOptions, Store as VuexStore } from 'vuex'
import { RootState } from '@/store/index'

type _FuncMap = { [k: string]: (...args: any) => any };

export type GenerateActionAugments<A, M extends _FuncMap> = Omit<ActionContext<A, RootState>, 'commit'> & {
  commit<K extends keyof M>(
    key: K,
    payload: Parameters<M[K]>[1]
  ): ReturnType<M[K]>;
}

export type GenerateStoreType<S, M extends _FuncMap, G extends _FuncMap, A extends _FuncMap> =
  Omit<VuexStore<S>, 'commit' | 'getters' | 'dispatch'>
  & {
  commit<K extends keyof M, P extends Parameters<M[K]>[1]>(
    key: K,
    payload: P,
    options?: CommitOptions,
  ): ReturnType<M[K]>;
}
  & {
  getters: {
    [K in keyof G]: ReturnType<G[K]>
  };
}
  & {
  dispatch<K extends keyof A>(
    key: K,
    payload: Parameters<A[K]>[1],
    options?: DispatchOptions,
  ): ReturnType<A[K]>;
};


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页