Vue - 使用Vuex进行状态管理

在Vue中使用Vuex进行状态管理,可以按照以下步骤操作:


1. 安装Vuex

使用npm或yarn安装Vuex:

npm install vuex@next --save  # Vue3
# 或 Vue2使用
npm install vuex@3 --save

2. 创建Store

src/store/index.js中定义Vuex store:

import { createStore } from 'vuex'; // Vue3
// Vue2: import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);

export default createStore({
  state: {
    count: 0
  },
  mutations: {
    increment(state, payload) {
      state.count += payload?.amount || 1;
    }
  },
  actions: {
    incrementAsync({ commit }, payload) {
      setTimeout(() => {
        commit('increment', payload);
      }, 1000);
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  },
  modules: {} // 可添加模块
});

3. 挂载Store到Vue应用

main.js中注入store:

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);
app.use(store);
app.mount('#app');

4. 在组件中使用Vuex

访问State和Getters

选项式API(Vue2/Vue3)

<template>
  <div>
    Count: {{ count }}, Double: {{ doubleCount }}
    <button @click="increment(5)">Add 5</button>
    <button @click="incrementAsync({ amount: 10 })">Async Add 10</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    ...mapMutations(['increment']),
    ...mapActions(['incrementAsync'])
  }
};
</script>

组合式API(Vue3)

<template>
  <div>
    Count: {{ count }}, Double: {{ doubleCount }}
    <button @click="increment(5)">Add 5</button>
    <button @click="incrementAsync({ amount: 10 })">Async Add 10</button>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';

const store = useStore();
const count = computed(() => store.state.count);
const doubleCount = computed(() => store.getters.doubleCount);

const increment = (amount) => store.commit('increment', { amount });
const incrementAsync = (payload) => store.dispatch('incrementAsync', payload);
</script>

5. 模块化(Module)

分割状态到模块中,例如src/store/modules/user.js

const userModule = {
  namespaced: true, // 启用命名空间
  state: () => ({
    name: 'Guest'
  }),
  mutations: {
    setName(state, name) {
      state.name = name;
    }
  }
};

export default userModule;

在store中引入模块:

import userModule from './modules/user';

export default createStore({
  modules: {
    user: userModule
  }
});

组件中使用(带命名空间):

// 选项式API
computed: {
  ...mapState('user', ['name'])
},
methods: {
  ...mapMutations('user', ['setName'])
}

// 组合式API
const name = computed(() => store.state.user.name);
const setName = (name) => store.commit('user/setName', name);

6. 最佳实践

  • Mutations:仅同步修改state
  • Actions:处理异步操作,通过commit触发mutations。
  • Getters:封装派生状态,避免重复计算。
  • 严格模式:开发时启用严格模式检测非法修改。
    export default createStore({
      strict: process.env.NODE_ENV !== 'production'
    });
    

总结

通过Vuex,可以集中管理跨组件的共享状态,保持数据流清晰。核心步骤包括创建store、定义状态变更逻辑(mutations/actions),并通过组件触发更新。模块化和命名空间能有效组织大型应用的状态管理。

posted @ 2025-03-04 17:11  箫笛  阅读(12)  评论(0)    收藏  举报