Vue学习笔记集--Vuex

Vuex

Vuex 是 Vue.js 的官方状态管理库,用于集中管理组件间共享的状态(数据)。

它通过单一数据源(store)实现数据的响应式管理和可预测的状态变更。


核心概念

概念作用特点
State存储应用的状态数据(类似组件的 data唯一数据源,响应式
Getters从 state 派生的计算属性(类似组件的 computed缓存结果,避免重复计算
Mutations唯一修改 state 的方法(同步操作)通过 commit 触发
Actions处理异步操作或复杂逻辑,提交 mutation 间接修改 state通过 dispatch 触发
Modules将 store 拆分为多个模块,便于管理大型应用的状态支持嵌套和命名空间(namespaced)

基本使用

安装与配置
npm install vuex@next  # Vue 3 使用 vuex@4
npm install vuex@3     # Vue 2 使用 vuex@3
创建 Store
// store/index.js
import { createStore } from 'vuex';const store = createStore({state: {count: 0,user: { name: 'Alice' }},getters: {doubleCount: (state) => state.count * 2,},mutations: {increment(state) {state.count++;},setUser(state, payload) {state.user = payload;}},actions: {async fetchUser({ commit }, userId) {const user = await api.getUser(userId);commit('setUser', user);}},modules: {// 模块化示例见下文}
});export default store;
挂载到 Vue 实例
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';const app = createApp(App);
app.use(store); // 注入全局 $store
app.mount('#app');

组件中使用 Vuex

State

存储数据

<template><div>{{ $store.state.count }}</div><div>{{ userName }}</div>
</template><script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';const store = useStore();
const userName = computed(() => store.state.user.name);
</script>

Vuex 的 state 是 Vuex 存储数据的地方,它提供了一种集中式的存储机制,让 Vue 组件能够方便地访问和共享状态。以下是 Vuex 的 state 的使用方法:

定义 state

在 Vuex store 中定义 state,state 是一个对象,用于存储应用的状态数据。

const store = new Vuex.Store({state: {count: 0,todos: [{ id: 1, text: 'Learn JavaScript', done: false },{ id: 2, text: 'Learn Vue', done: false },{ id: 3, text: 'Build a Vue App', done: false }]}
})
在组件中访问 state

可以通过 this.$store.state 或者 mapState 辅助函数在组件中访问 state 中的数据。

直接访问
export default {computed: {count() {return this.$store.state.count;},todos() {return this.$store.state.todos;}}
}
使用 mapState 辅助函数
import { mapState } from 'vuex';export default {computed: {...mapState(['count','todos'])}
}
修改 state

Vuex 的 state 是响应式的,但只能通过提交 mutation 来修改 state,直接修改 state 不会触发视图更新。

// 提交 mutation
this.$store.commit('increment');// 或者在组件中使用 methods
methods: {increment() {this.$store.commit('increment');}
}

对应的 mutation 定义如下:

const store = new Vuex.Store({state: {count: 0},mutations: {increment(state) {state.count++;}}
})
使用模块化 Vuex

在大型应用中,可以将 Vuex store 拆分成多个模块,每个模块有自己的 state、mutations、actions 等。

const moduleA = {namespaced: true,state: {count: 0},mutations: {increment(state) {state.count++;}}
}const store = new Vuex.Store({modules: {a: moduleA}
})

在组件中访问模块的 state:

computed: {count() {return this.$store.state.a.count;}
}

或者使用 mapState 辅助函数:

import { mapState } from 'vuex';export default {computed: {...mapState('a', ['count'])}
}
动态注册模块

可以在应用运行时动态注册模块,方便在需要时添加新的功能。

// 动态注册模块
store.registerModule('b', {state: {name: 'Module B'}
})// 在组件中访问
computed: {name() {return this.$store.state.b.name;}
}

通过以上方法,可以在 Vue 组件中方便地使用 Vuex 的 state,实现数据的集中管理和共享。

Getters

Vuex 中的 Getters 是用于从 Store 的 state 中派生出状态的计算属性,类似于组件内的 computed 属性。

基本用法
  • 定义 Getter:在 Store 的 getters 对象中定义函数,接收 state 作为第一个参数。

    const store = new Vuex.Store({state: {todos: [{ id: 1, done: true },{ id: 2, done: false }]},getters: {doneTodos: state => state.todos.filter(todo => todo.done)}
    });
    
  • 访问 Getter:通过 this.$store.getters.doneTodosmapGetters 辅助函数映射到组件计算属性。

    // 组件中
    computed: {...mapGetters(['doneTodos'])
    }
    
参数与依赖
  • 访问其他 Getter:通过第二个参数 getters 获取其他 Getter。

    getters: {doneCount: (state, getters) => getters.doneTodos.length
    }
    
  • 模块中的 Getter:在模块内,可访问模块的 state、根节点的 rootStaterootGetters

    getters: {combinedData(state, getters, rootState, rootGetters) {// 访问模块和根状态}
    }
    
动态参数
  • 返回函数:通过返回函数实现传参,例如根据 ID 查找特定项。

    getters: {getTodoById: state => id => state.todos.find(todo => todo.id === id)
    }
    // 使用:store.getters.getTodoById(2)
    
响应式与缓存
  • 响应式更新:当依赖的 state 变化时,Getter 自动重新计算。
  • 缓存机制:结果会被缓存,除非依赖的 state 发生变化,避免重复计算。

Mutation

在 Vuex 中,Mutations 是更改 store 中状态的唯一方式。它们是同步的事务,用于修改 state。以下是如何定义和使用 Mutations 的详细步骤:

定义和使用 Mutations
1. 定义 Mutations

在 Vuex store 中定义 Mutations。Mutations 是一个对象,其中的每个属性是一个函数,这些函数接收 state 作为第一个参数,或者通过参数解构来获取 state 和其他上下文信息。

const store = new Vuex.Store({state: {count: 0,todos: []},mutations: {// 简单的 mutationincrement(state) {state.count++;},// 带参数的 mutationincrementBy(state, amount) {state.count += amount;},// 修改 todossetTodos(state, todos) {state.todos = todos;}}
});
2. 在组件中提交 Mutations

可以在组件中通过 this.$store.commit 提交 Mutations。

<template><div><p>Count: {{ count }}</p><button @click="increment">Increment</button><button @click="incrementBy">Increment By 5</button><ul><li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li></ul></div>
</template><script>
export default {computed: {count() {return this.$store.state.count;},todos() {return this.$store.state.todos;}},methods: {increment() {this.$store.commit('increment');},incrementBy() {this.$store.commit('incrementBy', 5);},fetchTodos() {// 模拟异步操作setTimeout(() => {this.$store.commit('setTodos', [{ id: 1, text: 'Learn JavaScript' },{ id: 2, text: 'Learn Vue' }]);}, 1000);}},created() {this.fetchTodos();}
};
</script>
使用 mapMutations 辅助函数

为了简化代码,Vuex 提供了 mapMutations 辅助函数,可以将 store 中的 Mutations 映射到组件的方法中。

import { mapMutations } from 'vuex';export default {methods: {...mapMutations(['increment','incrementBy','setTodos'])}
};

这样,你就可以直接在组件中使用 incrementincrementBysetTodos 方法,而不需要显式地写 this.$store.commit

Mutations 的参数传递

如果需要向 Mutation 传递参数,可以在 commit 中作为第二个参数传入。

// 在组件中
this.$store.commit('incrementBy', 5);// 在 store 的 Mutations 中
incrementBy(state, amount) {state.count += amount;
}
Mutations 的返回值

Mutations 本身没有返回值,但你可以在提交 Mutation 后执行其他操作。

在 Mutations 中访问 state 和 getters

在 Mutations 中,可以通过参数解构来访问 state 和 getters。

mutations: {someMutation({ state, getters }) {console.log(state.count);console.log(getters.doubleCount);}
}
模块化 Vuex 中的 Mutations

在模块化 Vuex 中,Mutations 可以定义在模块内部。

const moduleA = {namespaced: true,state: {count: 0},mutations: {increment(state) {state.count++;}}
};const store = new Vuex.Store({modules: {a: moduleA}
});

在组件中提交模块的 Mutation:

this.$store.commit('a/increment');

或者使用 mapMutations

import { mapMutations } from 'vuex';export default {methods: {...mapMutations('a', ['increment'])}
};
总结
  • Mutations 是更改 Vuex store 中状态的唯一方式。
  • 在组件中通过 this.$store.commit 提交 Mutations。
  • 可以使用 mapMutations 辅助函数简化代码。
  • Mutations 可以接收参数,并在模块化 Vuex 中定义在模块内部。

Action

在 Vuex 中,actions 用于处理异步操作,并可以包含逻辑来提交 mutations,从而更新 state。actions 是 Vuex 中处理业务逻辑的主要场所。

定义和使用 actions
1. 定义 actions

在 Vuex store 中定义 actions。actions 是一个对象,其中的每个属性是一个函数,这些函数接收一个上下文对象作为参数,或者通过参数解构来获取 commitgetters 等。

const store = new Vuex.Store({state: {count: 0,todos: []},mutations: {increment(state) {state.count++;},setTodos(state, todos) {state.todos = todos;}},actions: {// 简单的 actionincrement({ commit }) {commit('increment');},// 带参数的 actionincrementBy({ commit }, amount) {commit('incrementBy', amount);},// 异步 actionfetchTodos({ commit }) {// 模拟异步操作return new Promise((resolve) => {setTimeout(() => {commit('setTodos', [{ id: 1, text: 'Learn JavaScript' },{ id: 2, text: 'Learn Vue' }]);resolve();}, 1000);});}}
});
2. 在组件中使用 actions

可以在组件中通过 this.$store.dispatch 触发 actions。

<template><div><p>Count: {{ count }}</p><button @click="increment">Increment</button><button @click="fetchTodos">Fetch Todos</button><ul><li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li></ul></div>
</template><script>
export default {computed: {count() {return this.$store.state.count;},todos() {return this.$store.state.todos;}},methods: {increment() {this.$store.dispatch('increment');},fetchTodos() {this.$store.dispatch('fetchTodos').then(() => {console.log('Todos fetched!');});}}
};
</script>
使用 mapActions 辅助函数

为了简化代码,Vuex 提供了 mapActions 辅助函数,可以将 store 中的 actions 映射到组件的方法中。

import { mapActions } from 'vuex';export default {methods: {...mapActions(['increment','fetchTodos'])}
};

这样,你就可以直接在组件中使用 incrementfetchTodos 方法,而不需要显式地写 this.$store.dispatch

actions 的参数传递

如果需要向 action 传递参数,可以在 dispatch 中作为第二个参数传入。

// 在组件中
this.$store.dispatch('incrementBy', 5);// 在 store 的 actions 中
incrementBy({ commit }, amount) {commit('incrementBy', amount);
}
actions 的返回值

dispatch 会返回一个 Promise,因此可以在触发 action 后使用 .then()async/await 来处理异步操作的结果。

this.$store.dispatch('fetchTodos').then(() => {console.log('Todos fetched!');
});
在 actions 中访问 state 和 getters

在 actions 中,可以通过上下文对象访问 state 和 getters。

actions: {someAction({ state, getters }) {console.log(state.count);console.log(getters.doubleCount);}
}
模块化 Vuex 中的 actions

在模块化 Vuex 中,actions 可以定义在模块内部。

const moduleA = {namespaced: true,state: {count: 0},mutations: {increment(state) {state.count++;}},actions: {increment({ commit }) {commit('increment');}}
};const store = new Vuex.Store({modules: {a: moduleA}
});

在组件中触发模块的 action:

this.$store.dispatch('a/increment');

或者使用 mapActions

import { mapActions } from 'vuex';export default {methods: {...mapActions('a', ['increment'])}
};
总结
  • actions 用于处理异步操作和业务逻辑。
  • 在组件中通过 this.$store.dispatch 触发 actions。
  • 可以使用 mapActions 辅助函数简化代码。
  • actions 可以接收参数,并返回 Promise。
  • 在模块化 Vuex 中,actions 可以定义在模块内部,并通过命名空间访问。

辅助函数(简化代码)

Vuex 提供 mapState, mapGetters, mapMutations, mapActions 辅助函数。

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

模块化(Modules)

定义模块
// store/modules/user.js
const userModule = {namespaced: true, // 启用命名空间state: () => ({ name: 'Guest' }),mutations: {setName(state, name) {state.name = name;}},actions: {login({ commit }, name) {commit('setName', name);}}
};export default userModule;
注册模块
// store/index.js
import userModule from './modules/user';const store = createStore({modules: {user: userModule}
});
访问模块内容
// 组件中使用命名空间访问
store.commit('user/setName', 'Charlie');
store.dispatch('user/login', 'David');// 辅助函数指定命名空间
...mapMutations('user', ['setName']),
...mapActions('user', ['login']),

核心原则

  1. 单一数据源:所有共享状态集中存储在 state 中。
  2. 状态只读:不允许直接修改 state,必须通过 mutations
  3. 同步修改mutations 必须是同步函数,确保状态变更可追踪。
  4. 异步操作:异步逻辑放在 actions 中,通过提交 mutations 修改状态。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/38265.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JSON在AutoCAD二次开发中应用场景及具体案例

配置文件的读取 在AutoCAD插件开发中&#xff0c;可能需要生成、修改、读取配置文件中一些参数或设置。JSON格式的配置文件易于编写和修改&#xff0c;且可以方便地反序列化为对象进行使用。 运行后效果如下 using Autodesk.AutoCAD.ApplicationServices; using Autodesk.Au…

自由学习记录(46)

CG语法的数据类型 // uint : 无符号整数&#xff08;32位&#xff09; // int : 有符号整数&#xff08;32位&#xff09; // float : 单精度浮点数&#xff08;32位&#xff09;&#xff0c;通常带后缀 f&#xff08;如 1.0f&#xff09; // half : 半精度浮…

解决Selenium滑动页面到指定元素,点击失效的问题

White graces&#xff1a;个人主页 &#x1f649;专栏推荐:Java入门知识&#x1f649; &#x1f439;今日诗词:君失臣兮龙为鱼&#xff0c;权归臣兮鼠变虎&#x1f439; ⛳️点赞 ☀️收藏⭐️关注&#x1f4ac;卑微小博主&#x1f64f; ⛳️点赞 ☀️收藏⭐️关注&#x1f4…

Vue基础

目录 -Vue基础- 1、插值表达式 {{}} 2、Vue核心特性&#xff1a;响应式 3、开发者工具Vue Devtools(极简插件下载) 4、Vue指令 v-text v-html v-bind v-on v-if v-show v-for v-model 5、Vue指令修饰符 .stop .prevent .capture .self .once .enter、.tab、…

收数据花式画图plt实战

目录 Python plt想把纵坐标化成对数形式代码 子图ax. 我又有ax scatter&#xff0c;又有ax plot&#xff0c;都要去对数 数字接近0&#xff0c;取对数没有定义&#xff0c;怎么办 创建数据 添加一个小的常数以避免对数未定义的问题 创建一个figure和一个子图ax 在子图a…

二项式分布(Binomial Distribution)

二项式分布&#xff08;Binomial Distribution&#xff09; 定义 让我们来看看玩板球这个例子。假设你今天赢了一场比赛&#xff0c;这表示一个成功的事件。你再比了一场&#xff0c;但你输了。如果你今天赢了一场比赛&#xff0c;但这并不表示你明天肯定会赢。我们来分配一个…

【算法工程】大模型开发之windows环境的各种安装

1. 背景 最近由于研究需要&#xff0c;我购置了两块3090显卡&#xff0c;以便在家中进行一些小规模的实验。为此&#xff0c;还更换了主机。当然&#xff0c;新系统上少不了要安装各种开发环境。从开发体验来看&#xff0c;macOS无疑更为流畅&#xff0c;但为了确保所有环境都能…

论文阅读笔记:Denoising Diffusion Probabilistic Models (2)

接论文阅读笔记&#xff1a;Denoising Diffusion Probabilistic Models (1) 3、论文推理过程 扩散模型的流程如下图所示&#xff0c;可以看出 q ( x 0 , 1 , 2 ⋯ , T − 1 , T ) q(x^{0,1,2\cdots ,T-1, T}) q(x0,1,2⋯,T−1,T)为正向加噪音过程&#xff0c; p ( x 0 , 1 , …

vscode查看文件历史git commit记录

方案一&#xff1a;GitLens 在vscode扩展商店下载GitLens 选中要查看的文件&#xff0c;vscode界面右上角点击GitLens的图标&#xff0c;选择Toggle File Blame 界面显示当前打开文件的所有修改历史记录 鼠标放到某条记录上&#xff0c;可以看到记录详情&#xff0c;选中O…

【数据挖掘】Python基础环境安装配置

【数据挖掘】Python基础环境安装配置 一、摘要二、安装Python3.13.2三、安装Jupyter Notebook四、安装Numpy和Pandas以及matplotlib五、安装scikit-learn库和seaborn库 一、摘要 本文主要介绍如何在Windows上安装Python3.13.2&#xff0c;然后基于该Python版本安装Jupyter not…

DeepSeek写打台球手机小游戏

DeepSeek写打台球手机小游戏 提问 根据提的要求&#xff0c;让DeepSeek整理的需求&#xff0c;进行提问&#xff0c;内容如下&#xff1a; 请生成一个包含以下功能的可运行移动端打台球小游戏H5文件&#xff1a; 要求 可以重新开始游戏 可以暂停游戏 有白球和其他颜色的球&am…

SpringMVC的执行流程剖析和源码跟踪

目录 一、常用组件:1、DispatcherServlet2、HandlerMapping3、Handler4、HandlerAdapter:5、ViewResolver6、View 二、SpringMVC的执行流程:1、流程图 在这里插入图片描述2、文字解析流程图3、ContextLoaderListener 三、源码跟踪1、doService()方法2、doDispatch()方法逻辑分解…

LeetCode hot 100 每日一题(13)——73. 矩阵置零

这是一道难度为中等的题目&#xff0c;让我们来看看题目描述&#xff1a; 给定一个 _m_ x _n_ 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 提示&#xff1a; m matrix.lengthn matrix[0].length1 < m, n …

ubuntu 解挂载时提示 “umount: /home/xx/Applications/yy: target is busy.”

问题如题所示&#xff0c;我挂载一个squanfs文件系统到指定目录&#xff0c;当我使用完后&#xff0c;准备解挂载时&#xff0c;提示umount: /home/xx/Applications/yy: target is busy.&#xff0c;具体的如图所示&#xff0c; 这种提示通常是表明这个路径的内容正在被某些进…

跟着StatQuest学知识06-CNN进行图像分类

目录 一、CNN特点 二、CNN应用于图像分类 &#xff08;一&#xff09;使用过滤器 &#xff08;二&#xff09;通过ReLU激活函数 &#xff08;三&#xff09;应用新的滤波器&#xff08;池化&#xff09; &#xff08;四&#xff09;输入 &#xff08;五&#xff09;输出…

MATLAB 控制系统设计与仿真 - 27

状态空间的标准型 传递函数和状态空间可以相互转换&#xff0c;接下来会举例如何有传递函数转成状态空间标准型。 对角标准型 当 G(s)可以写成&#xff1a; 即&#xff1a; 根据上图可知&#xff1a; 约当标准型 当 G(s)可以写成&#xff1a; 即&#xff1a; 根据上图…

Python网络编程入门

一.Socket 简称套接字&#xff0c;是进程之间通信的一个工具&#xff0c;好比现实生活中的插座&#xff0c;所有的家用电器要想工作都是基于插座进行&#xff0c;进程之间要想进行网络通信需要Socket&#xff0c;Socket好比数据的搬运工~ 2个进程之间通过Socket进行相互通讯&a…

C++ --- 多态

1 多态的概念 多态(polymorphism)的概念&#xff1a;通俗来说&#xff0c;就是多种形态。多态分为编译时多态(静态多态)和运⾏时多 态(动态多态)&#xff0c;这⾥我们重点讲运⾏时多态&#xff0c;编译时多态(静态多态)和运⾏时多态(动态多态)。编译时 多态(静态多态)主要就是我…

MQTT的安装和使用

MQTT的安装和使用 在物联网开发中&#xff0c;mqtt几乎已经成为了广大程序猿必须掌握的技术&#xff0c;这里小编和大家一起学习并记录一下~~ 一、安装 方式1、docker安装 官网地址 https://www.emqx.com/zh/downloads-and-install/broker获取 Docker 镜像 docker pull e…

ROS多机通信功能包——Multibotnet

引言 这是之前看到一位大佬做的集群通信中间件&#xff0c;突发奇想&#xff0c;自己也来做一个&#xff0c;实现更多的功能、更清楚的架构和性能更加高效的ROS多机通信的功能包 链接&#xff1a;https://blog.csdn.net/benchuspx/article/details/128576723 Multibotnet Mu…