The only way to update store status in vuex: submit Mutation
Mutation mainly consists of two parts:
String event type (type)
A callback function (handler), the callback function’s One parameter is state
Parameters are called mutations and are payloads
The first button clicks counter 5, the second button clicks counter 10
App.vue file<button>+5</button> <button>+10</button>
mutations: { incrementCount(state, count) { state.counter += count } },
methods: { addCount(count) { this.$store.commit("incrementCount", count); } }
Normal submission style
this.$store.commit("incrementCount", count);
incrementCount(state, count) { // state.counter += count console.log(count); }
##Special submission stylethis.$store.commit({
type: "incrementCount",
count
});
incrementCount(state, count) { // state.counter += count console.log(count); }
incrementCount(state, payload) { state.counter += payload.count console.log(payload.count); }
this.$store.commit({ type: "incrementCount", count });
mutations response rules
state: {
info: {
name: 2401,
age: 18
}
},
mutations: {
// 改变info中的值
infoChange(state) {
state.info.age = 10
}
},
<h2>{{$store.state.info}}</h2> <button>infoChange</button>
infoChange() { this.$store.commit("infoChange"); }
Add value to the original object
state.info['address'] = '地球';
Responsive methodVue.set(state.info, "address", '地球');
## Delete the value in the original object
Can't do the responsive method
delete state.info.age;
responsive methods
Vue.delete(state.info, "age")
mutations constant type
Official recommendation is to define the method names in mutations as constants, which is less error-prone and easier to manage and maintain.Create mutations-type.js file under the store file to store constantsexport const INCREMENT = "increment" export const DECREMENT = "decrement"
import { INCREMENT, DECREMENT } from "../store/mutations-type"
mutations: { [INCREMENT](state) { state.counter++; }, [DECREMENT](state) { state.counter--; }, }
import { INCREMENT, DECREMENT } from "../src/store/mutations-type";
methods: { add() { this.$store.commit(INCREMENT); }, sub() { this.$store.commit(DECREMENT); }, }
vue.js video tutorial
】The above is the detailed content of Detailed explanation of the use of Mutation in Vuex state management. For more information, please follow other related articles on the PHP Chinese website!