Vuex:是一个集中式状态管理工具,相当于react中的 redux
1) 主要解决的问题:大中型项目中复杂组件通讯问题
2) vuex操作流程:
dispatch commit
vue组件---------------->actions------------>mutations------->state-------->vue组件更新
3)vuex的重要概念: state:要保存的状态 mutations:是最终改变状态的方法集,mutations中的代码是同步执行的 actions:4)使用步骤: 第一步:先安装vuex npm install vuex --save 第二步:在src创建一个store目录,用来存放vuex相关文件 第三步:在store目录先创建一个index.js文件,做为vuex入口文件 第四步:在store目录的index.js中,写入下面的内容//引入vuex,vueimportVuexfrom'vuex';importVuefrom'vue';//让vue识别vuexVue.use(Vuex);//存储状态conststate={userinfo:{username:'张三',age:20,token:'1001'} }//将vuex暴露出去exportdefaultnewVuex.Store({ state });
第五步:在main.js中引入store,并在new Vue中注册
//引入vueximportstorefrom'./store';newVue({ ....... store, ........ });
第六步:如何获取和设置数据
获取:在对应组件的computed中处理
即: this.$store.state来获取
设置/修改数据:通过commit到mutations来修改state
如何提高vuex的使用体验:
1.优化state写法
import {matpState} from 'vuex'
在计算属性中添加下面的内容:
computed:{//组件的计算属性str() {return"hello"+this.msg },//vuex的数据...mapState({ address:'address', userinfo:'userinfo'}) }}
2.优化actions,mutations
import{ mapState,mapActions,mapMutations }from'vuex'; ...mapActions(['gomodify','aa','bb']), ...mapMutations(['setValue']),
3.隔离vuex各部分,提高可维护性
作者:奇妙雨
链接:https://www.jianshu.com/p/279bbf8eef7d
來源:简书
网友评论