快速入门——状态管理VueX

发布于:2025-02-28 ⋅ 阅读:(168) ⋅ 点赞:(0)

Vuex介绍

状态管理

每一个Vuex应用的核心都是一个store,与普通的全局对象不同的是,基于Vue数据与视图绑定的特点,当store中的状态发生变化时,与之绑定的视图也会被重新渲染。

store中的状态不允许被直接修改,改变store中的状态的唯一途径就是显示地提交,这可以让我们方便地跟踪每一个状态的变化。

在大型复杂应用中,如果无法有效地跟踪到状态的变化,将会对理解和维护代码带来极大的困难。

Vuex中有5个重要的概念:State,Getter,Mutation,Action,Module

State用于维护所有应用层的状态,并确保应用只有唯一的数据源.Mutation提供修改State状态的方法

//创建一个新的store实例

const store = createStore({

        state (){

                return {

                        count: 0

                }

        },

        mutations:{

                increment(state){

                        state.count++

                }

        }

})

 在组件中,可以直接使用this.$store.state.count访问数据,也可先用mapState辅助函数将其映射下来。

//单独构建的版本中辅助函数为Vuex.mapState

import { mapState } from 'vuex'

export default{

        coputed: mapState({

                count:state => state.count.

                countAlias: 'count',

                countPlusLocalState(state){

                       return state.count+this.localCount 

                }

        })

}

Mutation同步操作

在组件中,可以直接使用store.commit来提交mutation

method:{
    increment(){
        this.$store.commit('increment')
        console.log(this.$store.state.count)
    }
}

 也可以先用mapMutation辅助函数将其映射下来

methods: {
    ...mapMutations([
        'increment',
        'incrementBy'
        
    ])
},

Getter维护由State派生的一些状态,这些状态随着State状态的变化而变化

Action

类似于Mutation,适合做异步操作

Action不能直接修改状态,只能通过提交mutation来修改

const store = createStore({
    state: {
        count: 0
    },
    mutations: {
        increment(state){
            state++
        }
    },
    actions: {
        increment(context){
            context.commit('increment')
        }
    }


})