Vuex
Vuex
Vuex是vue项目中实现大范围数据共享的技术方案
作用:能够方便、高效地实现组件之间的数据共享
数据的存取一步到位,不需要层层传递
数据的流动非常清晰,记录每次操作的痕迹
存储在Vuex中的数据都是响应式的
安装配置
1 | //1.下包 |
State
概念:本质上就是一个对象
作用:存储全局共享的数据
1 | new Vuex.Store({ |
1 | <p> |
mapState
作用:简化属性名
将store中指定的数据,映射为当前组件的计算属性
1 | import {mapState} from 'vuex' |
Mutations
背景:直接修改会导致来源不明确的问题,不 方便调试和维护
概念:同步函数,专门用来变更Store中的数据
作用:所有组件都通过mutation修改,可以追踪state的每一次变化,确保修改来源的唯一性
1 | new Vuex.Store({ |
1 | methods:{ |
Payload
载荷就是参数的意思,通过载荷可以提高Mutation方法的通用性
1 | add(){ |
1 | mutations: { |
mapMutations
把Store中指定的mutation,映射为当前组件的methods
1 | <div @click="add(1)">+1</div> |
1 | import {mapMutations} from 'vuex' |
Actions
背景:为了保证state的每次变化可追踪,Mutation必须是同步函数
概念:专门用来处理Vuex中的异步操作
1 | new Vuex.Store({ |
1 | methods:{ |
mapActions
把Store中指定的action,映射为当前组件的methods
1 | <div @click="addAsync(10)">+10</div> |
1 | import {mapActions} from 'vuex' |
Getters
背景:组件中的计算属性复用性比较低
概念:Vuex中的计算属性
作用:当数据发生变化时,Getter的返回值就会自动更新
1 | new Vuex.Store({ |
1 | <p> |
mapGetters
把getter映射为当前组件的计算属性
1 | import {mapGetters} from 'vuex' |
Modules
背景:随着项目的工程量变大,数据越来越复杂
概念:按照模块化把不同业务的数据和方法进行封装
1 | // store/index.js |
1 | // store/shopcar.js |
namespaced
背景:不同子模块相同的名称方法被调用,会都调用一遍
概念:命名空间
作用:解决不同模块之间成员名称冲突的问题,建议每个模块都开
1 | // store/shopcar.js |
1 | <button @click="$store.commit('shopcar/test')"> |
mapState
1 | computed:{ |
- Title: Vuex
- Author: WGenji
- Created at : 2024-08-26 13:51:51
- Updated at : 2024-08-26 13:51:51
- Link: https://redefine.ohevan.com/2024/08/26/vue2/4.vuex/
- License: This work is licensed under CC BY-NC-SA 4.0.