解决vuex刷新状态初始化的方法实现
vuex五种基本对象
- state:存储状态(变量)
- getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用$sotre.getters.fun()
- mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
- actions:异步操作。在组件中使用是$store.dispath('')
- modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。
npminstallvuex-S//安装vuex
src/store/index.js
importVuefrom'vue'
importVuexfrom'vuex'
importtempfrom'@/store/modules/temp'
Vue.use(Vuex);//挂载在vue
conststore=newVuex.Store({
modules:{
temp,
},state:{
},getters:{
},mutations:{
},
});
exportdefaultstore;//抛出
src/store/modules/temp.js
constStorage=sessionStorage
consttempInfo={
state:{//设置全局访问的state对象
tempData:Storage['SET_TEMP_DATA']?JSON.parse(Storage['SET_TEMP_DATA']):{},//设置初始化的值(Storage中是否存在,存在则获取,不存在则默认赋值{})
},mutations:{//自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
SET_TEMP_DATA(state,tempData){
state.tempData=tempData
},
},actions:{
SetData({commit},tempData){
commit('SET_TEMP_DATA',tempData);//同步操作
Storage.setItem('SET_TEMP_DATA',JSON.stringify(tempData))
}
},getters:{//实时监听state值得变化(最新状态)
tempData:(state)=>{
returnstate.tempData
}
}
}
exportdefaulttempInfo;
main.js
importVuefrom'vue'
importAppfrom'./App'
importrouterfrom'./router'
importstorefrom'@/store/index'//vuex状态管理
Vue.config.productionTip=false
/*eslint-disableno-new*/
newVue({
el:'#app',
router,
store,//使用store
components:{App},
template:' '
})
src/index.vue
点击改变vuex值
其他
当然还可以使用vuex-persistedstate、vuex-along等这些第三方插件。
npmi-Svuex-persistedstate或npmi-Svuex-along
importVuefrom'vue'
importVuexfrom'vuex'
importtempfrom'@/store/modules/temp'
importcreatePersistedSattefrom'vuex-persistedstate'//引入
Vue.use(Vuex);
conststore=newVuex.Store({
modules:{
temp,
},state:{
},getters:{
},mutations:{
},
plugins:[createPersistedSatte()],//挂载插件
});
exportdefaultstore
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。