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

}

}

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({})

** 以 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

最后

除了简历做到位,面试题也必不可少,整理了些题目,前面有117道汇总的面试到的题目,后面包括了HTML、CSS、JS、ES6、vue、微信小程序、项目类问题、笔试编程类题等专题。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值