const store = new Vuex.Store({
state: {
obj:{
}
},
getters: {
nameInfo(state,getter){
return "姓名:" + state.obj.name
},
//第二个参数getters用于将getters下的其他对象拿来用
fullInfo(state,getters){
return getters.nameInfo + '年龄:' + state.obj.age
}
},
mutations: {
saveInfo(state,value){
//state里为初始值,value为你要存的值
state.obj= value
},
},
actions: {
//context(上下文):commit,dispatch,state,rootState,getters,rootGetters
async viewInfo(context, id){
const {
data } = await axios.get(`/api/residueDegree?id=${
id}`)
if (data.code === "0000") {
context.commit("saveInfo", data.data)
}
return data
}
}
})
//获取值
this.$store.state.obj
this.$store.getters.fullInfo
state 存放状态
getters 对state中的成员加工后传递给外界
mutations 对state成员操作(对数据的增加、删除、修改等等)
actions 对异步进行操作
modules 模块化状态管理
actions 与mutations区别
actions 提交的是 mutations,而不是直接变更状态。
actions 可以包含任意异步操作,使用dispatch方法,
mutation只能是同步操作,使用commit直接修改state里的值
let value ={
name:'nick',age:18 }
this.$store.commit("saveInfo",value)
this.$store.dispatch('viewInfo',123).then(()=>{
})
vuex中刷新页面数据会消失问题
const store = new Vuex.Store({
state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')): {
name:""
age:''
}
})
mounted() {
window.addEventListener('beforeunload', this.saveState)
},
methods: {
saveState() {
sessionStorage.setItem('state', JSON.stringify(this.$store.state))
}
}