浅谈vuex之mutation和action的基本使用

我们要实现的很简单,就是点击+1的count加一,点击-1的时候count-1

浅谈vuex之mutation和action的基本使用

一、mutation

在vue 中,只有mutation 才能改变state.  mutation 类似事件,每一个mutation都有一个类型和一个处理函数,因为只有mutation 才能改变state, 所以处理函数自动会获得一个默认参数 state. 所谓的类型其实就是名字,action去commit 一个mutation, 它要指定去commit哪个mutation, 所以mutation至少需要一个名字,commit mutation 之后, 要做什么事情,那就需要给它指定一个处理函数, 类型(名字) + 处理函数就构成了mutation. 现在test.js添加mutation.

const store = new Vuex.Store({ state: { count:0 }, mutations: { // 加1 increment(state) { state.count++; }, // 减1 decrement(state) { state.count-- } } })

Vue 建议我们mutation 类型用大写常量表示,修改一下,把mutation 类型改为大写

mutations: { // 加1 INCREMENT(state) { state.count++; }, // 减1 DECREMENT(state) { state.count-- } }

二、action

action去commit mutations, 所以还要定义action. test.js 里面添加actions.

const store = new Vuex.Store({ state: { count:0 }, mutations: { // 加1 INCREMENT(state) { state.count++; }, // 减1 DECREMENT(state) { state.count-- } }, actions: { increment(context) { context.commit("INCREMENT"); }, decrement(context) { context.commit("DECREMENT"); } } })

action 和mutions 的定义方法是类似的,我们要dispatch 一个action, 所以actions 肯定有一个名字,dispatch action 之后它要做事情,就是commit mutation, 所以还要给它指定一个函数。因为要commit mutation ,所以 函数也会自动获得一个默认参数context,  它是一个store 实例,通过它可以获取到store 实例的属性和方法,如 context.state 就会获取到 state 属性, context.commit 就会执行commit命令。

其实actions 还可以简写一下, 因为函数的参数是一个对象,函数中用的是对象中一个方法,我们可以通过对象的解构赋值直接获取到该方法。修改一下 actions

actions: { increment({commit}){ commit("INCREMENT") }, decrement({commit}){ commit("DECREMENT") } }

三、dispatch  action

现在就剩下dispatch action 了。什么时候dispatch action 呢? 只有当我们点击按钮的时候. 给按钮添加click 事件,在click 事件处理函数的中dispatch action.

这个时候我们需要新建一个操作组件,我们暂且命名为test.vue

<template> <div> <div> <button @click="add">+1</button> <button @click="decrement">-1</button> </div> </div> </template>

然后,我们在methods里面获取这两个操作事件

<script> export default { methods: { increment(){ this.$store.dispatch("increment"); }, decrement() { this.$store.dispatch("decrement") } } } </script>

当然上面这种写法比较麻烦,vuex还给我我们提供了mapActions这个函数,它和mapState 是一样的,把我们的 action 直接映射到store 里面的action中。

<script>     import {mapActions} from 'vuex' export default { methods: { ...mapActions(['increment', 'decrement']) } } </script>

如果事件处理函数名字和action的名字不同,给mapActions

提供一个对象,对象的属性是事件处理函数名字, 属性值是 对应的dispatch 的action 的名字。

<script> import {mapActions} from 'vuex' export default { methods: { // 这中写法虽然可行,但是比较麻烦 // 这时vue 提供了mapAction 函数, // 它和mapState 是一样的,把我们的 action 直接映射到store 里面的action中。 // increment () { // this.$store.dispatch('increment') // }, // decrement () { // this.$store.dispatch('decrement') // } // 下面我们使用一种比较简洁的写法 // ...mapActions(['increment', 'decrement']) /** 如果事件处理函数名字和action的名字不同,给mapActions 提供一个对象,对象的属性是事件处理函数名字, 属性值是 对应的dispatch 的action 的名字。 */ // 这里实际是为了改变事件的名字 ...mapActions(['decrement']), ...mapActions({ add: 'increment' }) } } </script>

这时候我们单击按钮,就可以看到count 发生变化。

最后附一张简单的图形解析,看起来应该能更直观一点

浅谈vuex之mutation和action的基本使用

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wygxwp.html