当前位置: 首页 > news >正文

【Vue2 ✨】Vue2 入门之旅(十):Vuex 入门

在前面几篇文章中,我们学习了 Vue Router。本篇将介绍 Vuex,它是 Vue 官方提供的状态管理库,用来解决组件之间共享数据的问题。


目录

  1. 为什么需要 Vuex
  2. 安装与引入
  3. 核心概念
    • state
    • getters
    • mutations
    • actions
  4. 一个最小示例
  5. 小结

为什么需要 Vuex

在 Vue 项目中,父子组件之间可以用 props$emit 进行通信,但当层级很深或多个组件需要共享数据时,就会变得复杂。
这时就需要一个 集中式的状态管理 —— Vuex。

优点:

  • 数据集中存放,方便管理
  • 任意组件都能方便访问
  • 改变数据有统一规范(mutation/action)

安装与引入

CDN 方式:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuex@3/dist/vuex.js"></script>

NPM 方式:

npm install vuex@3

核心概念

state

存放全局数据,相当于组件的 data

const store = new Vuex.Store({state: {count: 0}
})

组件中访问:

this.$store.state.count

getters

类似于计算属性,用来从 state 派生数据。

const store = new Vuex.Store({state: { count: 0 },getters: {double: state => state.count * 2}
})

组件中访问:

this.$store.getters.double

mutations

用于修改 state,必须是 同步操作

const store = new Vuex.Store({state: { count: 0 },mutations: {increment(state) {state.count++}}
})

组件中提交:

this.$store.commit('increment')

actions

用于处理异步逻辑,再通过 mutation 修改 state。

const store = new Vuex.Store({state: { count: 0 },mutations: {increment(state) {state.count++}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment')}, 1000)}}
})

组件中分发:

this.$store.dispatch('incrementAsync')

一个最小示例

<div id="app"><p>计数:{{ $store.state.count }}</p><button @click="$store.commit('increment')">+1</button><button @click="$store.dispatch('incrementAsync')">异步+1</button>
</div><script>
const store = new Vuex.Store({state: { count: 0 },mutations: {increment(state) {state.count++}},actions: {incrementAsync({ commit }) {setTimeout(() => commit('increment'), 1000)}}
})new Vue({el: '#app',store
})
</script>

在这里插入图片描述


小结

  1. Vuex 是集中式状态管理工具,解决多组件共享数据的问题。
  2. 核心概念:
    • state:存放数据
    • getters:派生数据
    • mutations:同步修改数据
    • actions:异步操作
  3. 通过 commit 提交 mutation,dispatch 分发 action。

📚至此,《Vue2 入门之旅》系列的基础十篇就完整啦!后续可以考虑写一些进阶篇,比如 响应式原理虚拟 DOM性能优化

http://www.dtcms.com/a/363969.html

相关文章:

  • 【机器学习学习笔记】Matplotlib 基本操作
  • 论文解读:基于 77 GHz FMCW 毫米波雷达的舱内占位检测
  • HDI是什么?与普通线路板有何区别?优势在哪?
  • java面试中经常会问到的多线程问题有哪些(基础版)
  • 宋红康 JVM 笔记 Day10|对象实例化
  • 2025全球绿色发展与健康生活方式高峰论坛 推动HLCC国际认证体系全球化实施
  • DuckDB新版rusty_sheet 插件测试
  • Android U Lmkd源码解析
  • 【Unity开发】丧尸围城项目实现总结
  • 自发自用分布式光伏电站进线柜防逆流测控保护装置
  • 什么是数据库管理系统(DBMS)?RDBMS和NoSQL又是什么?
  • vue2中如何使用Ant Design Vue 中的 Tooltip 文字提示
  • C#类对象映射AutoMapper
  • JUC 并发集合:高效处理多线程数据共享的利器
  • 开源的聚合支付系统源码/易支付系统 /三方支付系统
  • More Effective C++ 条款24:理解虚拟函数、多继承、虚继承和RTTI的成本
  • 第一次用pyQt6制作JSON小工具
  • =Windows下VSCode配置SSH密钥远程登录
  • C语言中奇技淫巧08-使用alloca/__builtin_alloca从栈上分配空间
  • 打工人日报#20250902
  • 自动化运维-ansible中的循环应用
  • 机器学习入门,支持向量机
  • etf期权亏几个点就爆仓了?
  • 37.Ansible循环+常用过滤器
  • docker-compose的使用
  • 让AI成为您的眼睛:星眸(StarGaze),为盲人朋友点亮前行之路
  • MySQL8.0 新特性随笔
  • 基于B_S结构的校园报修管理系统设计与实现(代码+数据库+LW)
  • 设置STS(Spring Tool Suite),在格式化代码时for循环中的冒号左右都加上一个空格
  • 移动端网页调试实战,Safari Web Inspector 深度使用与对比分析