This time I will bring you a detailed explanation of the use of vuex Actions, what are the precautions when using vuex Actions, the following is a practical case, let's take a look.
Action submits a mutation instead of directly changing the state. Action is asynchronous and mutation is synchronous.
Follow the example of learning with vuex---Introduction: Here is adding 10 and subtracting 1
1. The code in store.js is:
import Vue from'vue' import Vuex from'vuex' //使用vuex模块 Vue.use(Vuex); //声明静态常量为4 const state = { count : 4 }; const mutations = { add(state,n){ state.count +=n.a; }, sub(state){ state.count--; } }; const actions = { //2种书写方式 addplus(context){//可以理解为代表了整个的context context.commit('add',{a:10}) }, subplus({commit}){ commit('sub'); } }; //导出一个模块 exportdefaultnewVuex.Store({ state, mutations, actions })
2. In App.vue, the code is as follows:
<template> <p id="app"> <p id="appaaa"> <h1>这是vuex的示例</h1> <p>组件内部count{{count}}</p> <p> <button @click ="addplus">+</button> <button @click ="subplus">-</button> </p> </p> </p> </p> </template> <script> //引入mapGetters import {mapState,mapMutations,mapGetters,mapActions} from'vuex' exportdefault{ name:'app', data(){ return{ } }, computed:{ ...mapState([ "count" ]), }, methods:{ ...mapActions([ "addplus", "subplus" ]) } } </script> <style> </style>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
hammer.js implements the image gesture amplification function on the mobile side
js publisher-subscriber mode usage Detailed explanation
#What are the ways to introduce js into the page
The above is the detailed content of Detailed explanation of the use of vuex+Actions. For more information, please follow other related articles on the PHP Chinese website!