vuex study第三节Mutations修改状态

第一节我们初步见识了Mutations,这节我们再来详细看看,首先我们在store里面的mutations的方法加个参数

const mutations = {
    add(state,n){
        state.count+=n;
    },
    reduce(state){
        state.count--;
    }
}

然后是我们的Count.vue组件

<template>
    <div>
        <h1>{{ msg }}</h1>
        <!--直接引用store里的数据-->
        <h2>{{ $store.state.count }}--{{ count }}</h2>
        <!--这里就可以用我们的methods-->
        <button @click="add(10)">+</button>
        <button @click="reduce">-</button>
    </div>
</template>

<script>
    import store from '@/vuex/store'
    //这里多了个mapMutations
    import { mapState,mapMutations } from 'vuex'
    export default {
        data(){
            return {
                msg: 'Hello Vuex!'
            }
        },
        computed:mapState(['count']),
        //将mutations添加到menthods里面
        methods:mapMutations(['add','reduce']),
        //将store添加到实例
        store
    }
</script>

<style>
</style>

提示:这里我们可以看看我们调用方法时和声明方法的参数是有区别的

add(state,n);//声明

add(10);//调用,state是不用传的

//按我们第一节调用的,也是不一样的
$store.commit('add',10);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值