当前位置: 首页 > Web前端 > HTML

Vuex基础

时间:2023-04-02 14:41:54 HTML

vuex什么是Vuex?是Vue的状态管理模式。在使用vue的时候,在vue中组件之间传值是一件非常痛苦的事情。在vue中,我们可以使用vuex来保存我们需要管理的状态值。一旦更改了值,所有对该值的引用都会自动更新。是不是很方便好用?Vuex是专门为vue.js设计的状态管理模式。它集中存储和管理应用程序中所有组件的状态。Vuex还集成了Vue官方的调试工具。一个vuex应用的核心是store,一个容器,store包含了应用中的大部分状态。那么我们什么时候应用vuex呢?Vuex不是随便用的,小而简单的应用不太适合,因为使用Vuex繁琐冗余,使用简单的store模式更合适;对于vuex来说,更适合中大型的单页应用:多个视图用在同一个状态,不同的视图需要改变同一个状态。vuex状态管理实现了组件间的数据共享对应用中所有组件的状态进行集中存储和管理一个Vuex应用的核心是store(仓库,容器),它包含了你应用中的大部分状态(state)。传递参数的方法对于多层嵌套组件来说非常繁琐,而且对兄弟组件之间的状态传递也无能为力;使用父子组件通过事件直接引用或更改和同步多份状态通常会导致不可维护的代码。什么情况下应该使用Vuex适用于:中大型单页应用,无论在哪个组件,都可以获取状态/触发行为解决问题如下:①多个视图在同一个状态下使用:的方法传递参数适用于多层嵌套组件会很繁琐,对兄弟组件之间的状态传递无能为力通过事件同步状态通常会导致代码不可维护Command:在vueinstallvuexvuex项目文件夹下,actions只是一个架构概念,不是必须的Actions提交mutations而不是直接改变stateMutation:Actionsmustbeexecutedsynchronously:可以异步,但不能直接操作State创建一个vue项目,进入vueintwebpackweb,安装vuex,命令:npminstallvuex--save。store,index.jsimportVuefrom'vue'//importvueimportVuexfrom'vuex'//importvuex//usevuexVue.use(Vuex);//创建一个Vuex实例conststore=newVuex.store({})exportdefaultstore//exportstoremain.jsimportVuefrom'Vue'importAppfrom'./App'importrouterfrom'./router'importstorefrom'.store'Vue.config.productiontip=falsenewVue({el:'#app',store,router,components:{App},...})State,可以通过this.$store.state获取我们定义的数据在页面上:importVuefrom'vue'//importvueimportVuexfrom'vuex'//引入vuex//使用vuexVue.use(Vuex);//创建一个Vuex实例:conststore=newVuex.Store({state:{count:1}})exportdefaultstore//exportstore{{this.$store.state.count}}Getters相当于vue中的计算属性。getter的返回值会根据其依赖关系缓存起来,只有当其依赖值发生变化时才会重新计算。getter可以用来监听状态值的变化,返回计算结果。{{this.$store.getSateCount}}从'vue'导入Vue从'vuex'导入VuexVue.use(Vuex);conststore=newVuex.Store({state:{count:1;},getters:{getStateCount:function(state){returnstate.count+1;}}突变{{this.$store.state.count}}+-方法:{addFun(){this.$store.commit("add");},reductionFun(){this.$store.commit("reduction");}}index.jsimportVuefrom'vue'importVuexfrom'vuex'Vue.use(Vuex);//创建Vuex实例conststore=newVuex.store({state:{count:1},getters:{getStateCount:function(state){returnstatecount+1;}},mutations:{add(state){state.count=state.count+1;},reduction(state){state.count=state.count-1;}}})导出默认存储//导出storeActions:importVuefrom'vue'importVuexfrom'vuex'Vue.use(Vuex);conststore=newVuex.Store({state:{count:1;},getters:{getStateCount:function(state){returnstate.count+1;}}突变:{add(state){state.count=state.count+1;},reduction(state){state.count=state.count-1;}},actions:{addFun(context){context.commit("add");},reductionFun(上下文){context.commit("reduction");}}//vuemethods:{addFun(){this.$store.dispatch("addFun");//this.$store.commit("add");},reductionFun(){this.$store.dispatch("reductionFun");}}传值:方法:{addFun(){this.$store.dispatch("addFun");//this.$store.commit("add");},reductionFun(){varn=10;this.$store.dispatch("reductionFun",n);}}突变:{add(state){state.count=state.count+1;},reduction(state,n){state.count=state.count-n;}},actions:{addFun(context){context.commit("add");},reductionFun(context,n){context.commit("减少",n);}}