You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
3 Hrs
30 Min
22 Seg

Mutations

41/53
Resources

What are mutations in Vuex and what are they for?

Vuex mutations are essential for updating the state of an application in Vue. They do not update the state directly; instead, they allow you to log and track all applied changes, facilitating code debugging. This is crucial when multiple components modify state simultaneously, as it helps determine which component is making specific changes.

How do mutations work similar to events?

Mutations are defined in the store, and act as event handlers. Vue components execute these mutations using the commit method, which is equivalent to the emit method of events. This method specifies the name of the mutation to be executed, which allows the change to be registered and the state to be updated.

// Definition of mutations in store.jsmutations: { increment: (state) => state.count++, decrement: (state) => state.count--,}

How are mutations implemented in a Vue component?

  1. In the Vue component, the commit method is used to call mutations:
methods: { increment() { this.$store.commit('increment'); }, decrement() { this.$store.commit('decrement'); } }}
  1. So, when the related buttons are clicked, the count value in the state is updated and the component is automatically updated to reflect these changes.

What are payloads in a mutation?

In mutations, a payload can be used to pass configurable parameters to the state. Usually, this is an object that allows to carry more than one parameter, providing flexibility and customization in the operations.

Example with payloads

Suppose we need to increment the count value by a specific number:

 {mutations: { increment(state, payload = { number: 1 }) { state.count += payload.number; } }}

In this code fragment, when not receiving a payload, an empty object is allocated by default to avoid errors.

Implementation in a component

In the Vue component, it can be adapted to handle custom increments:

 {methods: { increment(payload) { this.$store.commit('increment', payload); } }// Using payload:this.increment({ number: 10 });

How to use mapMutations to optimize the code?

Vuex offers mapMutations, which allows to extract the mutations already defined in the store, avoiding code duplication in each component.

Implementing mapMutations

import { mapMutations } from 'vuex';
export default { methods: {...mapMutations(['increment', 'decrement']), incrementTen() { this.$store.commit('increment', { number: 10 }); } } } }}

With mapMutations, it is possible to combine store methods with those customized in the component, optimizing state management and code reuse.

If incrementTen needs to be used in multiple places, it can be brought into the store to improve accessibility and consistency.

Vuex and mutations provide a systematic way to manage data flow in Vue applications, making state management clearer and more efficient. By understanding and correctly applying these concepts, developers can build reactive and scalable applications more efficiently.

Contributions 15

Questions 4

Sort by:

Want to see more contributions, questions and answers from the community?

Mutaciones, La 煤nica forma de cambiar realmente el estado en una tienda Vuex es cometiendo una mutaci贸n. Las mutaciones de Vuex son muy similares a los eventos: cada mutaci贸n tiene un tipo de cadena y un controlador. La funci贸n de controlador es donde realizamos modificaciones de estado reales, y recibir谩 el estado como primer argumento

Pr谩cticamente el commit es una manera de mandar a llamar a una funci贸n definida en el store, y las mutaciones son como los m茅todos, y al ser reactivas pueden propagarse los cambios cada que estas cambien

GENIAL

Por fin logro entender Mutations, excelente Profesor.

Gracias ! Explicas super claro todo, vengo de react y justo ahora estoy trabajando en un proyecto con Vue y queria implementar flux, redux o algo parecido

Esto es genial.

Tengo una duda, si quisiera enviar los payload con mapMutation, c贸mo lo har铆a ?

Genial!

Explicaci贸n puntal del { } para importar cosas espec铆ficas del m贸dulo, y de los MapMutation y MapSatate.

Este curso y el de Laravel 2017 son de los mejores

Saludos. De casualidad el c贸digo de este ejemplo est谩 en un repositorio?

in Aplication

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>{{ count }}</p>
    <input type="number" placeholder="Escoge el n煤mero" v-model="chooseYourNumber">
    <br>
    <br>
    <button @click="decrementNum(1000)">-1000</button>
    <button @click="decrementNum(100)">-100</button>
    <button @click="decrementNum(10)">-10</button>
    <button @click="minus">-1</button>
    <button @click="init()">Choose</button>
    <button @click="increment">+1</button>
    <button @click="incrementNum(10)">+10</button>
    <button @click="incrementNum(100)">+100</button>
    <button @click="incrementNum(1000)">+1000</button>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";

export default {
  name: "HelloWorld",
  props: {
    msg: String
  },

  data() {
    return {
      chooseYourNumber: ''
    }
  },

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

  methods: {
    ...mapMutations([
      'increment',
      'minus'
    ]),
    incrementNum(num) {
      this.$store.commit('incrementPLUS', {
        number: num
      });
    },
    decrementNum(num) {
      this.$store.commit('minusPLUS', {
        number: num
      });
    },
    init() {
      this.$store.commit('init', parseFloat(this.chooseYourNumber));
    }
  }
};
</script>

Store

import Vuex from "vuex";
import Vue from 'vue';

Vue.use(Vuex);

//https://www.instagram.com/p/B-pmB-5BTRX/
const vueX = new Vuex.Store({
    state: {
        count: 0
    },

    mutations: {
        increment(state) {
            state.count ++;
        },
        minus(state) {
            state.count --;
        },
        incrementPLUS(state, ten = {}) {
            state.count += ten.number || 1
        },
        minusPLUS(state, asa = {}) {
            state.count -= asa.number || 1
        },
        init(state, num) {
            state.count = num
        }
    }
});

export default vueX;

Hab铆a escuchado o ten铆a entendido que las mutaciones eran como buenas pr谩cticas en vez de modificar directamente el state pero ahora veo que el commit es lo que lo hace tan importante.

Me parece super 煤til los map que trae Vuex! 馃挌

Si quieren revisar el codigo de esta clase y de las siguientes pueden hacerlo en este codesandbox

Solo a m铆 me pasa o este v铆deo se toma la vida en cargar?