Vuex implement state management
Background: Vue state management
How to introduce VUEX
1. Create a new file index.js used to directly reference VUEX
import Vue from 'vue'
import Vuex from 'vuex'
//直接使用VUEX
Vue.use(Vuex)
//创建vuex实例
const store = new Vuex.store({
})
export default store
2. Introduction of the store object main.js
import Vue from 'vue'
import App from 'App'
import router from './router'
import store from './store'
new Vuew({
el:'#app',
store,
router,
components:{
App
}
templete:'<App/>'
})
-
State declaration and use
const store = new Vuex.store({ state:{ count:1 } }) <h1> {{this.$store.state.count}} </h1>
-
getters
const store = new Vuex.store({ state:{ count:1 }, getters:{ getStateCount:function(state){ return state.count + 1 } } }) <h1> {{this.$store.getStateCount}} </h1>
How state management (change data)
-
Layout follows
<p>{{this.$store.count}} </p> <button @click="add">ADD</button> <button @click="minus">MINUS</button>
-
Corresponding logical layout
methods:{ add:function(){ this.$store.commit("add") }, minus:function(){ this.$store.commit("minus") } }
-
In vuex store objects
const store = new Vuex.store({ state:{ count:1 }, getters:{ getStateCount:function(state){ return this.$store.state + 1 } }, mutations:{ add:function(state){ state.count = state.count + 1 }, minus:function(){ state.count = state.count + 1 } } })
How elegant state management
-
Use actions
methods{ add:function(){ this.$store.dispatch("addF") }, minus:function(){ var n = 1; this.$store.dispatch("minusF" ,n) } } const store = new Vuex.store({ state:{ count:1 }, getters:{ getStateCount:function(state){ return state + 1 } }, mutations:{ add:function(state){ state.count = state.count + 1 }, minus:function(state,n){ state.count = (state.count -1)*(n+1) } }, actions:{ addF:function(context){ context.commit("add") }, minusF:function(context,n){ context.commit("minus",n) } } })
2. If we do not like the use of "this on the page. store.dispatch ( 'funname') "Such long writing, then we can use mapState, mapGetters, mapActions it will not be too much trouble;
<p>{{count1}} </p>
import {mapState,mapGetters,mapActions}from 'vuex'
couputed:{
mapSate{
count1:state=>store.count
}
}