vuex2.0

vuex是一个专为vue.js应用程序建立的状态管理模式,它采用集中式存储管理应用的所有组件的状态。

vuex中的几个重要的概念:store、state、mutation、action、getter

store:vuex将组件中的所有状态放到store中

state:组件状态,store的一次快照

mutation:vuex只允许提交一个mutation来改变state,mutation中只允许进行同步操作

action:调用commit触发mutation函数,可以进行异步操作

一个完整的store包括:state、mutation、action、getter

代码://创建store实例

const store = new Vuex.Store({
    state:{
        state1:'state1',
        state2:'state2'
    },
    mutations:{
        mutation1(state,payload){
            state.state1 = payload.value;
        },
        mutation2(state,payload){
            state.state2 = payload.value;
        }
    },
    actions:{
        action1(context,payload){
            context.commit('mutation2',payload);
        }
    }
})

//在根组件中注入store,在各子组件中调用: this.$store.state.state1(使用state),this.$store.commit('mutation1',payload)--(提交一个mutation),this.$store.dispatch('action1',payload) --(dispatch一个action)

推荐在computed中设置获取state值供组件使用,使用mapState()辅助函数,将组件中的方法映射为commit mutation/dispatch action,使用mapMutations/mapActions


//组件中使用


export default{
    computed:{
        ...mapState({
            items:"items",
            localItems(state){
                return state.state1 + this.data1;
            }
        })
    },
    methods:{
        ...mapMutations({
            'mutation1',
            'mutation2'
        })
        ...mapActions({
            'action1',
            'action2'
        })
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值