Vuex

Vuex 是一个用于管理Vue.js 状态管理库,可以更方便地在不同的组件间共享和修改状态

一、Vuex 基本概念

state: 存放公共数据的地方

getters:根据业务场景处理放回的数据

actions: 用于异步操作,通过分发操作触发mutation,间接更新state

mutations:唯一修改state的方法,修改过程是同步的

modules: 将store 分割成模块,便于管理复杂的状态

二、Vue 组件中使用Vuex

dispatch: 通过this.$store.dispath来分发action

commit:通过this.$store.commit 来提交mutation

三、Vuex 提供了一些辅助函简化代码:

mapState

mapGetters

mapActions

mapMutations

import {mapState,mapMutations,mapActions} from 'vuex'

export default{
      computed:{
              // 使用 mapState 将 store 中的状态映射到组建的计算属性中
               ...mapState(['count'])
      },
      methods:{
             ...mapMutaions(['increment']),
             ...mapActions(['incrementAsync']),
             add(){
                      //.....
            }
      }
}            

 

posted @ 2025-01-13 15:03  yangkangkang  阅读(21)  评论(0)    收藏  举报