跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Vuex状态管理
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
{{DISPLAYTITLE:Vuex状态管理}} '''Vuex''' 是 [[Vue.js]] 的官方状态管理库,用于集中式存储和管理应用的所有组件的状态。它采用单向数据流模式,确保状态变更可预测且易于调试,特别适合中大型单页应用(SPA)。 == 核心概念 == === 状态(State) === Vuex 使用单一状态树(Single State Tree)存储整个应用的状态,相当于组件的 "data" 但全局共享。 <syntaxhighlight lang="javascript"> const store = new Vuex.Store({ state: { count: 0, user: { name: 'Alice' } } }) </syntaxhighlight> === 获取状态 === 组件通过 <code>this.$store.state</code> 或 <code>mapState</code> 辅助函数访问状态: <syntaxhighlight lang="javascript"> // 选项式API computed: { count() { return this.$store.state.count } } // 组合式API import { computed } from 'vue' import { useStore } from 'vuex' const store = useStore() const count = computed(() => store.state.count) </syntaxhighlight> === 变更状态(Mutations) === 唯一修改状态的方式是提交 mutation(同步操作): <syntaxhighlight lang="javascript"> mutations: { increment(state, payload) { state.count += payload.amount } } // 组件中调用 this.$store.commit('increment', { amount: 10 }) </syntaxhighlight> === 异步操作(Actions) === Action 通过提交 mutation 间接变更状态,可包含任意异步操作: <syntaxhighlight lang="javascript"> actions: { async fetchUser({ commit }, userId) { const user = await api.getUser(userId) commit('SET_USER', user) } } // 组件中调用 this.$store.dispatch('fetchUser', 'user123') </syntaxhighlight> === 派生状态(Getters) === 相当于 store 的计算属性: <syntaxhighlight lang="javascript"> getters: { doubleCount: (state) => state.count * 2, filteredTodos: (state) => (status) => { return state.todos.filter(todo => todo.status === status) } } // 使用 this.$store.getters.doubleCount this.$store.getters.filteredTodos('completed') </syntaxhighlight> == 数据流图示 == <mermaid> graph LR A[组件] -->|dispatch| B(Action) B -->|commit| C(Mutation) C -->|mutate| D(State) D -->|render| A </mermaid> == 模块化(Modules) == 大型应用可将 store 分割为模块: <syntaxhighlight lang="javascript"> const userModule = { namespaced: true, state: () => ({ profile: {} }), mutations: { /* ... */ } } const store = new Vuex.Store({ modules: { user: userModule } }) // 访问模块状态 this.$store.state.user.profile </syntaxhighlight> == 实际案例 == '''电商购物车实现''' <syntaxhighlight lang="javascript"> // store.js export default new Vuex.Store({ state: { cartItems: [], inventory: {} }, mutations: { ADD_TO_CART(state, product) { const item = state.cartItems.find(i => i.id === product.id) item ? item.quantity++ : state.cartItems.push({ ...product, quantity: 1 }) } }, actions: { async loadInventory({ commit }) { const products = await fetch('/api/products') commit('SET_INVENTORY', products) } }, getters: { cartTotal: state => { return state.cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0) } } }) </syntaxhighlight> == 与Pinia的对比 == Vuex 4.x 与 [[Pinia]](Vuex 的替代方案)主要区别: {| class="wikitable" |- ! 特性 !! Vuex !! Pinia |- | Vue 版本 || 2.x/3.x || 3.x+ |- | 类型支持 || 需要额外配置 || 开箱即用 |- | 模块系统 || 需要命名空间 || 自动命名空间 |- | 语法复杂度 || 较高 || 更简洁 |} == 最佳实践 == 1. 遵循单一职责原则拆分模块 2. 使用常量命名 mutation 类型 3. 表单处理建议: <syntaxhighlight lang="javascript"> // 使用双向绑定+计算属性 computed: { message: { get() { return this.$store.state.obj.message }, set(value) { this.$store.commit('UPDATE_MESSAGE', value) } } } </syntaxhighlight> == 数学表达 == 状态更新可表示为: <math>\sigma_{t+1} = M(\sigma_t, a)</math> 其中: * <math>\sigma</math> 为状态 * <math>M</math> 为 mutation 函数 * <math>a</math> 为 action 负载 == 常见问题 == '''Q: 何时该用 Vuex?''' A: 当多个组件需要共享状态或存在深层次组件通信时。 '''Q: 可以直接修改 state 吗?''' A: 严格模式下会报错,必须通过 mutation 修改。 {{Vue.js相关主题}} [[Category:计算机科学]] [[Category:面试技巧]] [[Category:前端框架]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)
该页面使用的模板:
模板:Vue.js相关主题
(
编辑
)