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
}
目录:
分包的时候我们往往需要手动在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
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)
这种方式是我比较喜欢,也是项目在用的,文件划分清晰,使用可读性高,类型推断好。
代码 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’
? []
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:前端)
最后
前端CSS面试题文档,JavaScript面试题文档,Vue面试题文档,大厂面试题文档,需要的读者可以戳这里获取!
,18年进入阿里一直到现在。**
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-w5b2AhwG-1712553069575)]
[外链图片转存中…(img-TVhFr2Zd-1712553069576)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
[外链图片转存中…(img-VH6Ufaed-1712553069577)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:前端)
最后
前端CSS面试题文档,JavaScript面试题文档,Vue面试题文档,大厂面试题文档,需要的读者可以戳这里获取!
[外链图片转存中…(img-yaXam97u-1712553069577)]
[外链图片转存中…(img-BnuTdFyS-1712553069578)]