This is the 6th day of my mutation in the Gengwen Challenge
mutation
Each mutation has a string event type (type) and a callback function (callback).
use
//store.js
// Take a look at the following example
import Vue from 'vue'
import Vuex from 'vuex'
// To use that must be introduced
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
title: ' '
},
mutations: {
// Accept the event name to save the data to vuex
book(state, plyLode){ state.title = plyLode//plyLode is the saved data}}})Copy the code
/ / a template
<template>
<div name='Joe' @click='itemClick'>
</template>
<script>
export default {
name: "a".data(){
return {
title: 'I'm shared data passing through.'}},methods: {
itemClick() {
New codestore.com MIT (' event name ', passed data)
this.$store.commit('book'.this.title)
},
},
};
</script>
Copy the code
First we define a div click event in template A, after which we will save our data through VUex.
. mapMutations
Mutations also support the abbreviation… MapMutations uses the same as the previous State getter
<script>
import { mapMutations } from 'vuex'
export default {
name: a,
computed: {
...mapMutations(['book '])}}; </script>Copy the code
Action
The Action function accepts a context object with the same methods and properties as the store instance, so you can submit a mutation by calling context.mit. Or get state and getters via context.state and context.getters.
//store.js
// Take a look at the following example
import Vue from 'vue'
import Vuex from 'vuex'
// To use that must be introduced
Vue.use(Vuex)
const store = new Vuex.Store({
// omit other code...
mutations: {
// Accept the event name to save the data to vuex
addN(state, plyLode){ state.num = plyLode//plyLode is the saved data}}// Define an action method
actions: {
// Define an addNasync method with two parameters: the first is the fixed 'context' and the second is the parameter to be passed
addNasync(context, stpe) {
setTimeout(() = > {
context.commit('addN', step)
}, 1000})}})Copy the code
methods: {
itemClick() {
// this.$store. Dispatch (' event name ', passed data)
this.$store.dispatch('addN'.5)}},Copy the code
. mapActions
As before, the shortcut for action is… mapActions
methods: {
itemClick() {
...mapActions(['addN'])}},Copy the code
The action was submitted to mutation to change the state and cannot change the state on its own. Only mutation can change the state.