vue的存储管理模式,困扰了我很久,一直没有下定决心好好学习。我在vue项目组一直使用localStorage存储信息.setItem(key,value);//存储信息localStorage.getItem(key);//获取信息这里插个小彩蛋,当你想存储信息为一个对象,首先要将对象转成字符串JSON.stringify(arr);,得到值后,将字符串转成JSON.parse(string)//对象转字符串letarr=[1,2,3];JSON.stringify(arr);//'[1,2,3]'typeofJSON.stringify(arr);//string//stringtoobjectletstring='[1,2,3]';console.log(JSON.parse(string))//[1,2,3]console.log(typeofJSON.parse(string))//object```好了,话不多说,我们抓紧时间开始学习vuexstroe1、vuex组件安装命令:npminstallvuex--save2。创建一个store.js文件并导入我们的vueximportVuefrom'vue';从'vuex'导入Vuex;导入之后,需要使用vue.useimportVue.use(Vuex)3.导入成功了,我们来剖析一下:首先,我们需要在我们的main.js中引入我们的storeimportstorefrom'./store.js'newVue({el:'#app',router,store})首先,我们开始一个简单的demo在store.js中,我们首先实例化并创建我们直接通过this.$store.state.count2.getters:getter相当于vue中的computed属性,getter的返回值根据其依赖关系进行缓存,只有当它的依赖值发生变化时才会重新计算。这里我们可以通过定义vuex的Getter来获取。Getter可用于监视和更改state中的值并返回计算结果。这里我们修改HelloWorld.vue文件如下:我们在store.js的getters方法中放了一个getChangeState方法。方法中传入的state参数是外层的state,方法中获取参数来改变state中count的值。exportdefaultnewVuex.Store({state:{count:1},getters:{getChangeState:function(state){returnstate.count+1;}}})这个.$store.getters.getChangeState可以直接在里面获取页面代码count通过getters方法后显示count值。3.Mutations:在vuex中,如果想改变store中变量的状态,唯一的办法就是mutations,那么既然我们在页面上可以拿到state中的值,那怎么改变呢?让我们了解突变。首先,我们向页面添加一个事件来改变状态:使用this.$store.commit("addCount");调用store.js中的addCount方法。同样,如果你想将参数传递给addCount,你可以这样做。$store.commit("addCount",n);可以直接修改状态中的状态,而Mutations可以直接修改状态中的状态;Action支持异步操作,而Mutations只能是同步操作。接下来,让我们看一下操作。先在我们的childstore中写好actions方法,使用参数countext.commit调用mutations方法addCount,exportdefaultnewVuex.Store({state:{count:1},getters:{getChangeState:function(state){returnstate.count+1;}},mutations:{addCount(state,n){returnstate.count=state.count+n;}},actions:{addCountFun(countext,n){countext.commit("addCount",n);}}})如何调用helloWord.vue中的actions方法?使用this.$store.dispatch("addCountFun",n)我是页面直接从页面获取的count----{{this.$store。状态。count}}
页面直接获取this.$store.getters.getChangeState的值----{{this.$store.getters.getChangeState}}
