Vuex的学习笔记三:核心概念Action和Getter的理解和使用

一.Action

1.1Action的自我介绍

Action用于处理异步任务
如果通过异步操作变更数据,必须通过Action
,而不是使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。

Action 提交的是 mutation
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation。

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count:0, //在state中存储一个count数据
  },
  mutations: {
    add(state){
      //变更state中的count数据
      state.count++
    }
  },
  actions:{
    asyncAdd(context){
       setTimeout(() => { //这里用定时器假设是异步操作
         context.commit('add') //这里还是触发mutations中的add方法更改count数据
       }, 1000)
    }
  }
})

实践中,我们会经常用到 ES2015 的 参数解构来简化代码(特别是我们需要调用 commit 很多次的时候),所以也可以写成下面代码:

 actions:{
	 asyncAdd({commit}){
	     setTimeout(() => { 
	        commit('add')
	     }, 1000)
	 }
  }

1.2组件触发Action中的异步函数

第一种方式:通过 this.$store.dispatch 方法触发

  methods:{
     addCount(){
       this.$store.dispatch('asyncAdd')
     }
  }

第二种方式:mapActions辅助函数

<template>
   <div> 
      <!-- 这里点击事件可以直接写成actions函数事件名  -->
      <button @click = "asyncAdd"></button> 
   </div>
</template>

  //从Vuex中按需导入mapActions函数
import { mapActions} from 'vuex'

<script>
export default {
    methods: {
    //将指定的actions函数,映射为当前组件的methods函数
      ...mapActions(['asyncAdd'])
    },
}
</script>

1.3组件触发Action异步时携带参数

首先要先更改一下mutations和actions中的函数,如下:

mutations: {
    add(state,num){
      //变更state中的count数据
      state.count += num
    }
},
actions:{
	 asyncAdd({commit},num){
	     setTimeout(() => { 
	        commit('add',num)
	     }, 1000)
	 }
 }

然后还是通过 this.$store.dispatch 方法触发

  methods:{
     addCount(){
      var num = 5
       this.$store.dispatch('asyncAdd',num )
     }
  }

二.Getter

2.1Getter的自我介绍

Getter用于对Store中的数据进行加工处理形成新的数据;

  1. Getter可以对Store中已有的数据进行加工处理形成新的数据,类似Vue的计算属性
  2. Store中的数据发生变化,Getter的数据也会跟着发生变化
  3. Getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
 state: {
   count:0, //在state中存储一个count数据
 },
 getters: {
   newCount:state => {
     return  ‘最新值是’+ state.count
   }
 }
})

2.2组件访问Getter的数据

第一种方式:通过 this.$store.getters方法触发

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

第二种方式:mapActions辅助函数

  //从Vuex中按需导入mapGetters 函数
import { mapGetters } from 'vuex'

<script>
export default {
    computed: {
    //将 store 中的 getter 映射到组件计算属性
      ...mapGetters (['newCount'])
    },
}
</script>
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端探险家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值