目录结构(如图)
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)
})
}
调用getters方法
先import引入mapGetters方法
格式:import { mapGetters } from 'vuex'
在vue的computed下调用 ...mapGetters([ ]) 中括号中写入要获取的getters方法
调用mutations方法
先import引入mapMutations方法
在vue的methods下调用 ...mapMutations({ }) 大括号中写入要修改的数据的mutations方法
调用actions方法
先import引入mapActions方法
在vue的methods下调用 ...mapActions([ ]) 中括号中写入要修改的数据的actions方法
刷新浏览器vuex数据重置解决方法
只需写在app.vue中 读取、存储sessionStorage的状态信息
通过 window.addEventListener 事件绑定可以监听页面刷新 ‘beforeupload’
created() {
//在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem('store')) {
this.$store.replaceState(
Object.assign(
{},
this.$store.state,
JSON.parse(sessionStorage.getItem('store'))
)
)
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('store', JSON.stringify(this.$store.state))
})
}