Vue - Vue2使用Vuex进行状态管理

在 Vue 2 中使用 Vuex 主要分为以下步骤:

1. 安装 Vuex

npm install vuex@3 --save  # Vue 2 对应 Vuex 3
# 或
yarn add vuex@3

2. 创建 Vuex Store

在项目中创建 src/store/index.js 文件:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  // 核心配置
  state: {       // 状态数据
    count: 0,
    user: null
  },
  mutations: {   // 同步修改状态
    INCREMENT(state) {
      state.count++
    },
    SET_USER(state, user) {
      state.user = user
    }
  },
  actions: {     // 异步操作
    login({ commit }, credentials) {
      return api.login(credentials).then(user => {
        commit('SET_USER', user)
      })
    }
  },
  getters: {     // 计算属性
    doubleCount: state => state.count * 2
  },
  modules: {     // 模块化(可选)
    // cart: cartModule
  }
})

3. 注入 Vue 实例

main.js 中挂载 store:

import Vue from 'vue'
import App from './App.vue'
import store from './store'

new Vue({
  store,  // 注入所有组件
  render: h => h(App)
}).$mount('#app')

4. 在组件中使用

访问状态 (State)

<template>
  <div>
    <p>Count: {{ $store.state.count }}</p>
    <p>User: {{ $store.state.user?.name }}</p>
  </div>
</template>

使用 Getter

<template>
  <p>Double: {{ $store.getters.doubleCount }}</p>
</template>

提交 Mutation (同步)

<script>
export default {
  methods: {
    increment() {
      this.$store.commit('INCREMENT')
    }
  }
}
</script>

分发 Action (异步)

<script>
export default {
  methods: {
    login() {
      this.$store.dispatch('login', {
        username: 'test',
        password: '123456'
      })
    }
  }
}
</script>

5. 使用辅助函数 (简化代码)

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

export default {
  computed: {
    // 展开运算符混入
    ...mapState(['count']),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    ...mapMutations(['INCREMENT']),
    ...mapActions(['login']),
    
    // 使用:
    handleClick() {
      this.INCREMENT()  // 直接调用
    }
  }
}
</script>

6. 模块化 (大型项目)

// store/modules/user.js
export default {
  namespaced: true,  // 启用命名空间
  state: () => ({ profile: null }),
  mutations: { /* ... */ },
  actions: { /* ... */ }
}

// store/index.js
import user from './modules/user'

export default new Vuex.Store({
  modules: {
    user
  }
})

组件中使用带命名空间的模块:

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions('user', ['fetchProfile']),
    
    // 直接调用
    getUser() {
      this.fetchProfile()
    }
  }
}
</script>

最佳实践建议:

  1. 修改状态只通过 mutations
  2. 异步操作使用 actions
  3. 复杂逻辑使用 getters 封装
  4. 大型项目务必使用模块化
  5. 使用常量命名 mutations/actions
    // mutation-types.js
    export const SET_USER = 'SET_USER'
    

调试工具

启用 Vue Devtools 查看 Vuex 状态变化和时间旅行调试功能

注意:Vue 2 请始终使用 Vuex 3.x 版本,Vuex 4.x 是为 Vue 3 设计的

posted @ 2025-07-18 14:43  箫笛  阅读(70)  评论(0)    收藏  举报