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

教你学习vue-4(vuex)

时间:2023-04-05 23:34:10 HTML5

1.先了解一下vuex是做什么用的。管理统一的组件状态状态。每个应用程序将只包含一个商店实例。单个状态树允许我们直接定位任何特定的状态片段,并在调试期间轻松获取整个当前应用程序状态的快照。2.如何实现vuexhasseveralobjectsstate=>mapStategetters=>mapGettersactions=>mapActionsmutations=>mapMutationsmoudle3.state(injectintostore)Vuex提供了一种机制,通过store选项将状态从根组件“注入”到每个子组件在组件中(需要调用Vue.use(Vuex)):constapp=newVue({el:'#app',//将store对象提供给store选项,可以将store实例注入所有subcomponentsstore,components:{Counter},template:`

`})通过在根实例中注册store选项,store实例将被注入进入到根组件下面的所有子组件中,并且可以通过this.$store访问子组件。当我们需要时刻跟踪state值的变化时,可以通过组件的计算机属性来判断,然后使用mapState。映射的方法。computed:{localComputed(){/*...*/},//使用对象展开运算符将这个对象混合到外部对象中...mapState({//...})}4.getters(both是方法)Vuex允许我们在商店中定义“getter”(可以认为是商店的计算属性)。就像计算属性一样,getter的返回值根据其依赖项进行缓存,并且仅在其依赖项的值发生变化时才重新计算。Getter接受状态作为第一个参数。mapGetters辅助函数只是将store中的getter导入{mapGetters}from'vuex'exportdefault{computed:{//使用对象展开运算符将getter混合到计算对象中...mapGetters(['doneTodosCount','anotherGetter',//...])}}5.mutation改变Vuexstore中的状态的唯一方法是提交mutation并调用方法store.commit('increment')注意使用常量代替ofMutations事件类型exportconstSOME_MUTATION='SOME_MUTATION'//store.jsimportVuexfrom'vuex'import{SOME_MUTATION}from'./mutation-types'conststore=newVuex.Store({state:{...},mutations:{//我们可以使用ES2015风格的计算属性命名来使用常量作为函数名[SOME_MUTATION](state){//mutatestate}}})Mutation必须是一个同步函数mapMutationsimport{mapMutations}from'vuex'exportdefault{//...方法:{...mapMutations(['increment',//将`this.increment()`映射到`this.$store.commit('increment')`//`还支持mapMutations有效负载:'incrementBy'//将`this.incrementBy(amount)`映射到`this.$store.commit('incrementBy',amount)`]),...mapMutations({add:'increment'//将`this.add()`映射到`this.$store.commit('increment')`})}}6.ActionActioncommitIt是突变而不是直接改变状态。Action可以包含任何异步操作。上下文不是商店实例本身。Action函数接受一个与store实例具有相同方法和属性的context对象,因此您可以调用context.commit提交一个mutation,或者通过context.state和context.getters获取状态和getters。actions:{increment({commit}){commit('increment')}}mapActions映射到组件import{mapActions}from'vuex'exportdefault{//...methods:{...mapActions(['increment',//将`this.increment()`映射到`this.$store.dispatch('increment')`//`mapActions`也支持负载:'incrementBy'//映射`this.incrementBy('increment')`for`this.$store.dispatch('incrementBy',amount)`]),...mapActions({add:'increment'//将`this.add()`映射到`this.$store.dispatch('增量')`})}}7.模块概念Vuex允许我们将商店拆分为模块。每个模块都有自己的状态、变异、动作和吸气剂。类似于redux中的reducer,处理每个组件对应的state。constmoduleA={state:{...},mutations:{...},actions:{...},getters:{...}}constmoduleB={state:{...},mutations:{...},actions:{...}}conststore=newVuex.Store({modules:{a:moduleA,b:moduleB}})store.state.a//->moduleAstore的状态.state.b//->moduleB的状态rootState对于模块内部的action,本地状态通过context.state暴露出来,根节点状态为context.rootState。rootState可以获取所有mudule中的状态值constmoduleA={//...actions:{incrementIfOddOnRootSum({state,commit,rootState}){if((state.count+rootState.count)%2===1){commit('increment')}}}}这个还是要看更多官方demo