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 来修改状态。

相关推荐
祈澈菇凉35 分钟前
什么是 Vue 的自定义事件?如何触发和监听?
前端·javascript·vue.js
2301_766536052 小时前
调试无痛入手
开发语言·前端
@大迁世界3 小时前
构建 Next.js 应用时的安全保障与风险防范措施
开发语言·前端·javascript·安全·ecmascript
IT、木易4 小时前
ES6 新特性,优势和用法?
前端·ecmascript·es6
is今夕4 小时前
postcss.config.js 动态配置基准值
javascript·vue.js·postcss
青茶绿梅*24 小时前
500字理透react的hook闭包问题
javascript·react.js·ecmascript
计算机软件程序设计4 小时前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
指尖时光.4 小时前
【前端进阶】01 重识HTML,掌握页面基本结构和加载过程
前端·html
前端御书房5 小时前
Pinia 3.0 正式发布:全面拥抱 Vue 3 生态,升级指南与实战教程
前端·javascript·vue.js