Vue组件学习 | 二、Vuex组件

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式和库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。以下是 Vuex 的基本用法

Vuex 基本用法

安装 Vuex

首先,你需要安装 Vuex。如果你使用的是 npm,可以使用以下命令:

bash 复制代码
npm install vuex --save

创建 Vuex Store

创建一个新的 Vuex store 实例,它将包含所有状态(state)、改变状态的方法(mutations)和获取状态的函数(getters)。

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

Vue.use(Vuex)

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

在 Vue 组件中使用 Vuex Store

你可以在 Vue 组件中使用 mapStatemapGettersmapActionsmapMutations 辅助函数来使用 Vuex store。

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

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

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

Vuex 模块

Vuex 允许你将 store 分割成模块,每个模块拥有自己的 state、mutations、actions、getters,甚至是嵌套子模块。

javascript 复制代码
const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
})

Vuex 严格模式

Vuex 允许你以严格模式运行,这在开发过程中非常有用,因为它会阻止你对状态的直接更改。

javascript 复制代码
const store = new Vuex.Store({
  // ...
  strict: process.env.NODE_ENV !== 'production'
})

Vuex 插件

Vuex 允许你使用插件来扩展 store 的功能。插件可以监听 Vuex store 的 mutation 并响应它们。

javascript 复制代码
const myPlugin = store => {
  store.subscribe((mutation, state) => {
    // 调用 API 或者其他响应
  })
}

const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})

以上就是 Vuex 的基本用法。

你可以在 Vuex 官方文档 中找到更多高级用法和配置选项。

相关推荐
jz_ddk1 小时前
[学习] 卫星导航的码相位与载波相位计算
学习·算法·gps·gnss·北斗
阿珊和她的猫1 小时前
`require` 与 `import` 的区别剖析
前端·webpack
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
谎言西西里1 小时前
零基础 Coze + 前端 Vue3 边玩边开发:宠物冰球运动员生成器
前端·coze
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
努力的小郑2 小时前
2025年度总结:当我在 Cursor 里敲下 Tab 的那一刻,我知道时代变了
前端·后端·ai编程
华清远见成都中心2 小时前
人工智能要学习的课程有哪些?
人工智能·学习
GIS之路2 小时前
GDAL 实现数据空间查询
前端
hssfscv2 小时前
Javaweb学习笔记——后端实战2_部门管理
java·笔记·学习
OEC小胖胖2 小时前
01|从 Monorepo 到发布产物:React 仓库全景与构建链路
前端·react.js·前端框架