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

相关推荐
Keya13 分钟前
MacOS端口被占用的解决方法
前端·后端·设计模式
RainbowSea18 分钟前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
vue.js·spring boot·后端
moyu8421 分钟前
解密Vue组件中的`proxy`:此Proxy非彼Proxy
前端
用户849137175471624 分钟前
为什么大模型都离不开SSE?带你搞懂第1章〈SSE技术基础与原理〉
前端·网络协议·llm
随笔记27 分钟前
react中函数式组件和类组件有什么区别?新建的react项目用函数式组件还是类组件?
前端·react.js·typescript
在星空下30 分钟前
Fastapi-Vue3-Admin
前端·python·fastapi
FogLetter31 分钟前
面试官问我Function Call,我这样回答拿到了Offer!
前端·面试·openai
Juchecar32 分钟前
CSS布局模式详解 - 初学者完全指南
前端
emojiwoo34 分钟前
React 状态管理:useState 与 useDatePersistentState 深度对比
前端·javascript·react.js