目錄結(jié)構(gòu)(如圖)
1. index.js
? ??????import?Vue?from?'vue'
????????import?Vuex?from?'vuex'
????????import?state?from?'./state'
????????import?*?as?getters?from?'./getters'
????????import?mutations?from?'./mutations'
????????import?*?as?actions?from?'./actions'
????????import?user?from?'./module/user'
????????Vue.use(Vuex)
????????export?default?new?Vuex.Store(
????????????state,
????????????getters,
????????????mutations,
????????????actions,
????????????modules:?{
????????????????user
????????????}
? ? ? ?})
2.state.js
? ??????const?state?=?{
????????????name:?'Bates',
????????????age:?29
????????}
????????export?default?state
3.getters.js
? ??????export?const?name?=?state?=>?{
????????????return?state.name
????????}
????????export?const?age?=?state?=>?state.age
4.mutations_types.js
? ??????export?const?SET_NAME?=?'SET_NAME'
????????export?const?SET_AGE?=?'SET_AGE'
5.mutations.js
? ??????import?*?as?types?from?'./mutations_types'
????????const?mutations?=?{
????????????[types.SET_NAME](state,?name)?{
????????????????state.name?=?name
????????????},
????????????[types.SET_AGE](state,?age)?{
????????????????state.age?=?age
????????????}
????????}
????????export?default?mutations
6.actions.js
import?*?as?types?from?'./mutations_types'
export?const?editNameAge?=?({?commit,?state?},?{?name,?age?})?=>?{
????return?new?Promise((resolve,?reject)?=>?{
????????setTimeout(()?=>?{
????????????commit(types.SET_NAME,?name)
????????????commit(types.SET_AGE,?age)
????????????resolve()
????????},?2000)
????})
}
調(diào)用getters方法
先import引入mapGetters方法
格式:import { mapGetters } from 'vuex'
在vue的computed下調(diào)用 ...mapGetters([ ]) 中括號(hào)中寫入要獲取的getters方法
調(diào)用mutations方法
先import引入mapMutations方法
在vue的methods下調(diào)用 ...mapMutations({ }) 大括號(hào)中寫入要修改的數(shù)據(jù)的mutations方法
調(diào)用actions方法
先import引入mapActions方法
在vue的methods下調(diào)用 ...mapActions([ ]) 中括號(hào)中寫入要修改的數(shù)據(jù)的actions方法
刷新瀏覽器vuex數(shù)據(jù)重置解決方法
只需寫在app.vue中 讀取需纳、存儲(chǔ)sessionStorage的狀態(tài)信息?
通過 window.addEventListener 事件綁定可以監(jiān)聽頁面刷新 ‘beforeupload’
created()?{
????????//在頁面加載時(shí)讀取sessionStorage里的狀態(tài)信息
????????if?(sessionStorage.getItem('store'))?{
????????????this.$store.replaceState(
????????????????Object.assign(
????????????????????{},
????????????????????this.$store.state,
????????????????????JSON.parse(sessionStorage.getItem('store'))
????????????????)
????????????)
????????}
????????//在頁面刷新時(shí)將vuex里的信息保存到sessionStorage里
????????window.addEventListener('beforeunload',?()?=>?{
????????????sessionStorage.setItem('store',?JSON.stringify(this.$store.state))
????????})
????}