VueX状态管理器cnpmivuexaxios-S1创建Vuex仓库importVuefrom'vue'importVuexfrom'vuex'vue.use(Vuex)conststore=newVueX.store({state:{//Storestate},mutations:{//唯一修改状态的地方,这里不要做逻辑处理}})exportdefaultstore2在入口文件main下引入storeimportstorefrom'./store/index.js'。js将store放在根实例中供全局使用newVue({el:'#app',store,components:{App},template:})开始使用store(以home组件为例))的Vuex的使用也是循序渐进的。可以从最简单的开始使用,然后根据经验和技术的增加,逐渐加强使用。如果按照级别来计算vuex的使用,可以从最基础的t1级别开始。先总结一下前三个版本是最基础的,其他的以后有时间再总结一下。T1level1.hoome/script.js中请求数据importVuefrom'vue'importaxiosfrom'axios'exportdefault{mounted(){axios.get('请求数据的接口').then((res)=>{this.$store.commit('changeList',res.data)})//changeList相当于调用store.mutations中定义的修改state的方法//res.data是在改变state的时候要修改的这里需要传递数据。.catch((err)=>{console,log(err)})}}2。defineimportVuefrom'vue'importVuexfrom'vuex'instore/index.jsvue.use(Vuex)conststore=newVueX.store({state:{//Storestatelist:[]//存储一个空的array},mutations:{//唯一修改state的地方,这里不做逻辑处理//定义一个修改list的方法//state指的是上面存放list的对象,data就是请求的数据当请求的数据发送出去时changeList(state,data){state.list=data//将请求的数据赋给列表}}})exportdefaultstore3.Renderinhome/index.vue//渲染数据时,直接通过this.store.state.list从store中获取数据//也可以从其他组件使用此方法,无需重新设置数据get{{item.name}}注:(如果我们在home中获取的数据组件可以在其他组件中使用,但是当页面刷新时默认进入首页,相当于修改了数据,然后点击其他页面也可以有数据,如果我们获取的数据在用户组件需要在home组件中使用,刷新页面时不会显示数据,因为此时用户组件中改变数据的方法还没有触发,所以数据为空,当用户页面点击了,就会有数据,然后这时候点击首页,我们就可以在首页组件中看到用户组件中获取到的数据。这个问题的解决方法可以是将数据保存到本地或者在首页请求数据)T2层在渲染页面的时候,我们需要通过this.store.state来获取数据。这种写法太长了,不是很容易用computedattributes结合mapState来解决这个问题1.在home/script.js中操作importVuefrom'vue'importmapStatefrom'vuex'importaxiosfrom'axios'exportdefault{computed:{//mapState是一个辅助函数...mapState(['list'])},mounted(){axios.get('请求数据的接口').then((res)=>{this.$store.commit('changeList',res.data)}).catch((err)=>{console,log(err)})}}2在home/index.vue
v-for='itemoflist':key='item.id'>{{item.name}}T3级别使用常量替换事件类型(便于查看状态,便于维护)1创建mutation-type.jsexportconstCHANGE_LIST=understore'CHANGE_LIST'2在store/index.js中引入mutation-type.jsimportVuefrom'vue'importVuexfrom'vuex'import{CHANGE_LIST}from'./mutation-type.js'vue.use(Vuex)conststore=newVueX.store({state:{list:[]//存储一个空数组},mutations:{//我们可以使用Es6风格的计算属性命名函数,使用一个常量作为函数名[CHANGE_LIST](state,data){state.list=data//将请求的数据赋值到列表中}}})导出默认存储3在home/script.js中导入从“vue”导入Vue从“vuex”导入mapState从“axios”导入axios从“../../store/mutation-type.js”导入{CHANGE_LIST}exportdefault{computed:{//mapState是一个辅助函数...mapState(['list'])},mounted(){axios.get('请求数据的接口').then((res)=>{this.$store.commit(CHANGE_LIST,res.data)}).catch((err)=>{console,log(err)})}}