vuex整理

    科技2026-02-28  7

    Vuex

    定义:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

    简单的说: Vuex就是创建了一个状态库,将各组件之间数据存在状态库中, 将组件与组件之间的通信变成了组件与状态之间通信

    state:用来定义多组件之间的共享状态

    Mutations:用来修改state数据,只能在Mutations中更改vuex状态

    actions:用来定义一个方法在实例中进行异步请求

    getters:相当于计算属性,当我们得到state的值之后,使用getters,将这些基本的值进行组合加工,得到我们需要的值

    let store = new Vuex.Store({ state:{ //就是用来定义多组件之间的共享状态 isTabbarShow:true, cinemaList:[...] }, mutations:{ show(state){ state.isTabbarShow = true }, hide(state){ state.isTabbarShow = false } }, getters:{ //类似于computed计算属性 只不过里面的数据依赖于vuex的状态 getCinemaListFive(state){ return state.cinemaList.slice(0,5) }, }, actions:{ xxAsync(context){ axios.get().then(res=>{ context.commit("方法",参数) } } } }) created(){ this.$store.commit("hide") //commit调用mutations方法 console.log(this.$store.state.isTabbarShow) //获取state中的数据 console.log(this.$store.dispatch("xxAsync")) //获取异步请求的数据 console.log(this.$store.getters.getCinemaListFive) //获取getters方法得到的数据 }

    vuex辅助函数

    mapState,mapGetters,mapActions,mapMutations

    mapState

    mapState这个辅助函数就是为了方便获取vuex中的状态,本来获取状态 this.$store.state.xxx,使用辅助函数后直接使用this.xxx调用即可。

    mapGetters

    这个辅助函数与mapState的用法一模一样

    mapActions

    这个辅助函数用法与上面一致,但是需要定义在methods里面

    created(){ if(this.cinemaList.length === 0){ // this.$store.dispatch("cinema/getCinemaListAction") this.getCinemaListAction() } }

    mapMutations

    这个辅助函数用法与上面一致的用法

    import {mapState,mapGetters,mapMutations,mapActions} from "vuex" methods:{ //mapMutations,mapActions要放在methods中 ...mapActions("cinema",["getCinemaListAction"]), ...mapMutations("tabbar",["show","hide"]), } computed:{ //mapState,mapGetters要放在computed中 ...mapGetters(["getCinemaListFive"]), ...mapState(["cinemaList"]), } created(){ console.log(this.cinemaList) this.getCinemaListAction() }

    后续如果你的computed中有跟vuex的同名的,需要通过这种方式设置

    ...mapState({ aaa:state=>state.cinemaList }),
    Processed: 0.009, SQL: 9