Vuex

Vuex

起男 1 2026-04-12

Vuex

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

简单来说,状态管理可以理解成为了更方便的管理组件之间的数据交互,提供了一个集中式的管理方案,任何塑胶都可以按照指定的方式进行读取和改变数据

使用

安装vuex:

npm install --save vuex

配置vuex文件:

import { createStore } from 'vuex'

export default createStore({
    //数据放在这里
    state:{
        count:0
    }
})

在主文件中引入vuex:

import store from './store/index'

createApp(App).use(store).mount('#app')

在项目中使用:

<p>count = {{ $store.state.count }}</p>

快捷读取

使用vuex提供的mapState:

<script>
import { mapState } from 'vuex';

export default {
  //专门读取vux的数据
  computed:{
    ...mapState(["count"])
  }
}
</script>

页面中使用:

<p>{{ count }}</p>

Getter

对vuex中的数据进行过滤

定义getters:

import { createStore } from 'vuex'

export default createStore({
    //数据放在这里
    state:{
        count:0
    },
    getters:{
        getCount(state){
            return state.count > 0 ? state.count : "数据异常"
        }
    }
})

使用getters:

<template>
  <p>{{ $store.getters.getCount }}</p>
  <p>{{ getCount }}</p>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  //专门读取vux的数据
  computed:{
    ...mapGetters(["getCount"])
  }
}
</script>

Mutation

更改vuex的store中的状态的唯一方法是提交mutation

定义Mutation:

import { createStore } from 'vuex'

export default createStore({
    state:{
        count:0
    },
    mutations:{
        //参数num可选,没有使用时不填即可
        addCount(state,num){
            state.count+=num
        }
    }
})

使用Mutation:

<template>
  <p>hello = {{ $store.state.count }}</p>
  <button @click="add">增加</button>
</template>

<script>
import { mapMutations } from 'vuex';

export default {
  methods:{
    ...mapMutations(["addCount"]),
    add(){
      //基本写法
      // this.$store.commit("addCount",10)
      //便携写法
      this.addCount(20)
    }
  }
}
</script>

Action

类似于mutation,不同在于:

  • action提交的是mutation,而不是直接变更状态
  • action可以包含任意异步操作

定义Action:

import { createStore } from 'vuex'

export default createStore({
    state:{
        count:0
    },
    mutations:{
        setCount(state,num){
            state.count+=num
        }
    },
    actions:{
        asyncAddCount({commit}){
            commit("setCount",11)
        }
    }
})

使用Action:

<template>
  <p>hello = {{ $store.state.count }}</p>

  <button @click="asyncAdd">异步增加</button>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods:{
    ...mapActions(["asyncAddCount"]),
    asyncAdd(){
      // this.$store.dispatch("asyncAddCount")
      this.asyncAddCount()
    }
  }
}
</script>