Actions - Tylung/vue-apuntes GitHub Wiki

Las actions son como metodos que pueden ser asíncronos, disparan un commit de una mutation

  • Dispatch action
  • Commit mutation

Archivo: src/helpers/getRandomInt

La funcion getRandomInt es asíncrona, tarda 1 seg en realizar su trabajo y devuelve un numero random del 1 al 20

const getRandomInt = () => {
    return new Promise ( resolve => {

        const rndInt = Math.floor((Math.random() * 20) + 1)

        setTimeout(() => {
            resolve( rndInt )
        }, 1000)
    })
}

export default getRandomInt

La importamos en el archivo index.js

Archivo: src/store/index.js

import getRandomInt from '../helpers/getRandomInt'

export default createStore({

    state: {
        count: 1,
        lastMutation: 'none'
        lastMutation: 'none',
        isLoading: false,
        lastRandomInt: 0
    },

    mutations: {
@@ -17,6 +19,18 @@ export default createStore({
        incrementBy( state, val) {
            state.count += val
            state.lastMutation = 'íncrementBy'
            state.lastRandomInt = val
        },

    },

    actions: {
        async incrementRandomInt( context ) {

            const randomInt = await getRandomInt()

            context.commit('incrementBy', randomInt )

        }
    }
})

En actions llamamos a la funcion incrementRandomInt y le pasamos el context que tiene informacion sobre el contexto del store o donde nos encontremos, por eso hacemos context.commit('incrementBy', randomInt), que llama a la mutation incrementBy pasandole como parámetro el numero random

En el componente del counter agregamos un nuevo boton que lanze un metodo del componente

Archivo: src/components/counter-vuex.vue

<template>
...
 <button @click="incrementRandomInt">Random</button>
...
<template/>

<script>
 export default {
   ...
    methods: {
            increment() {
                this.$store.commit('increment')
            },
            incrementBy( ) {
                this.$store.commit('incrementBy', 5)
            },
            incrementRandomInt() {
                this.$store.dispatch('incrementRandomInt')
           },
        }
}
<script/>

El metodo incrementRandomInt lanza un dispatch a la accion incrementRandomInt

⚠️ **GitHub.com Fallback** ⚠️