Vue 中如何模块化使用 Vuex

在 Vue 中使用 Vuex 进行模块化管理状态非常简单,以下是一个基本的代码示例:

在 main.js 中引入 Vuex:

javascript 复制代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 创建 store
const store = new Vuex.Store({
  // 定义状态
  state: {
    count: 0
  },
  // 定义 mutations
  mutations: {
    increment(state) {
      state.count++
    }
  },
  // 定义 actions
  actions: {
    increment(context) {
      context.commit('increment')
    }
  },
  // 定义 getters
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }
})

// 将 store 注入到 Vue 实例中
new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

然后在组件中使用 Vuex:

html 复制代码
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

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

export default {
  computed: {
    // 将 Vuex 的 state 映射为组件的计算属性
    ...mapState(['count']),
    // 将 Vuex 的 getters 映射为组件的计算属性
    ...mapGetters(['doubleCount'])
  },
  methods: {
    // 将 Vuex 的 actions 映射为组件的方法
    ...mapActions(['increment'])
  }
}
</script>

这样就可以在组件中通过 count 获取状态值,通过 doubleCount 获取计算属性值,并通过 increment 方法触发 mutation 来修改状态。

相关推荐
IT_陈寒13 小时前
Vue这个坑我跳了两次,原来问题出在这
前端·人工智能·后端
kyriewen13 小时前
我用 50 行代码重写了 React Router 核心,终于搞懂了前端路由原理
前端·javascript·react.js
WebInfra14 小时前
Rspack 2.1 发布:React Compiler 提速 10 倍!
前端
李明卫杭州14 小时前
CSS 媒体查询详解:一文掌握响应式设计的核心技术
前端
lichenyang45315 小时前
从 H5 按钮到 OpenHarmony 能力调用:我如何理解 ASCF 的运行链路
前端
下家16 小时前
我放弃了 Vue/React,选择自研框架
前端·前端框架
Asize16 小时前
HTML5 Canvas 基础:从按帧动画到 ECharts 数据可视化
前端·javascript·canvas
默_笙16 小时前
🎄 后端给我一堆扁平数据,我 10 行代码把它变成了树
前端·javascript
Mahut16 小时前
我用 Electron + FFmpeg 做了一个本地视频处理工作站 ClipForge
前端·ffmpeg·electron
前端Hardy16 小时前
又一个 AI 神器火了!
前端·javascript·后端