vuex访问状态对象

state

公用的数据都写在这里面

const state={
    count:1
}

在组件中获取使用时可以通过三种方式
组件中引入辅助函数(当然先引入store.js,下面引入就不提了)

import { mapState } from 'vuex'

第一种

通过计算属性

computed: {
    count () {
      return this.$store.state.count
    }
  }

在模板中直接使用 {{count}} 就可以了

第二种
这就用到了辅助函数mapState ,同样需要计算属性

   computed:mapState({
     count:state=>state.count
   })

模板中使用方法同上

第三种

其实为辅助函数简写的方法

 computed:mapState(['count']),

当有多个函数时可以按下面这样写,用到了扩展运算符样式为(…)为es6方法可以把对象展开

 computed:{
    ...mapState(['count']),
    ***,
    ***
  },

模板中使用方法同上

Mutations

store.js文件中创建Mutations 常量

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

模板中的使用

<p>
   <button @click="$store.commit('add')">+</button>
   <button @click="$store.commit('reduce')">-</button>
</p>

上篇已经提到了这里就不做多提,这里主要提下简写方式,以及传送参数
由于是方法所以在methods中引入辅助函数
组件中引入

      import { mapMutations} from 'vuex';

      methods:{
        ...mapMutations(['add','reduce']),
      }

模板中使用

     <button class="btn" @click="add">+</button>
     <button class="btn" @click="reduce">-</button>

传参数

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

两个参数第一个为state,第二个才是为传递的参数

组件模板中

 //非简写
  <button class="btn" @click="$store.commit('add',10)">+</button>
  <button class="btn" @click="$store.commit('reduce',15)">-</button>
  //简写
  <button class="btn" @click="add(10)">+</button>
  <button class="btn" @click="reduce(15)">-</button>

Getter

相当于一个过滤器,在store.js中加入getter常量

const getters = {
  count:function(state){
    return state.count +=100;
  }
};

组件模板中引入辅助函数mapGetters并在计算属性

computed:{
    ...mapState(['count']),
    ...mapGetters(["count"])
  },

这样每回修改都会加上100

Action

Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。

创建action常量

const actions ={
    addAction(context){
        context.commit('add',10)
    },
    reduceAction({commit}){
        commit('reduce')
    }
}

context:上下文对象,这里你可以理解称store本身。
{commit}:直接把commit对象传递过来,可以让方法体逻辑和代码更清晰明了。
组件中引入


  <button class="btn" @click="addAction">+</button>
  <button class="btn" @click="reduceAction">-</button>

    <script>
         import {mapActions} from 'vuex';
         methods:{
           ...mapActions(['addAction','reduceAction'])
          }
      </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值