前段时间因为需要用到Vue,特地研究了一下。但是时间太短没接触vuex,所以今天空余时间看了下vuex,做了一个小demo,记录下vuex的简单使用过程。什么是Vuex?Vuex是专门为vue.js应用开发的一种状态管理模式。当多个视图依赖于同一个状态或多个视图可以更改某个状态时,共享状态被提取并全局管理。以下是在src目录下创建存储文件夹的计数器示例。src/store.jsimportVuefrom'vue'从'vuex'导入VuexVue.use(Vuex)conststore=newVuex.Store({state:{count:0,show:''},getters:{counts:(state)=>{returnstate.count}},突变:{increment:(state)=>{state.count++},decrement:(state)=>{state.count--},changTxt:(state,v)=>{state.show=v}}})exportdefaultstorestate是我们需要的状态,状态只能通过提交突变来改变,例如:handleIncrement(){this.$store.commit('increment')}with带payload的提交方法:changObj(){this.$store.commit('changTxt',this.obj)}当然payload也可以是一个对象,所以可以提交多个参数。changObj(){this.$store.commit('changTxt',{key:''})}引入store.jsimportstorefrom'./store/store'exportdefaultnewVue({el:'#app',router,store,components:{App},template:' {{$store.state.count}}{{$store.state.show}}
