Loading... <h2>前言</h2> <h4>Vuex 是什么?</h4> <p>官方文档里面是这么说的:</p> <pre><code>Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。</code></pre> <p>可以理解为 Vuex 是一个数据管理框架</p> <h4>Vuex 都有什么</h4> <p>state(存放状态数据的地方)</p> <p>getters(可以理解为 store 的计算属性)</p> <p>mutations(改变 state 中数据的方法(同步修改数据))</p> <p>actions(改变 state 中数据的方法(异步修改数据))</p> <p>modules(当 state 过大时,可使用 modules 将其分割成模块)</p> <h4>Vuex 的使用</h4> <pre><code class="language-vue">state: { // 我们在 state 中定义一个 count count: 0 }, // 在组件中使用 import { useStore } from 'vuex' import { computed } from 'vue' export default { setup () { const store = useStore() const count = computed(() => store.state.count) return { count } } }</code></pre> <p><strong>修改state中的数据</strong></p> <pre><code class="language-vue"> // 第一步使用 dispatch 方法,派发一个 action,名字为 countAdd const countAdd = () => { store.dispatch('countAdd') } actions: { // 第二步, store 感知到触发了一个 countAdd 的 action ,执行 countAdd 方法 countAdd () { // 第三步,提交一个 commit 触发一个 mutation this.commit('countAdd') } }, mutations: { // 第四步,对应的 mutation 被执行 countAdd () { // 第五步,在 mutation 里进行修改数据 this.state.count++ } },</code></pre> <p>如果更改的数据,没有异步操作的话,也可以直接提交一个 commit 进行修改数据</p> <pre><code class="language-vue"> const countAdd = () => { store.commit('countAdd') } mutations: { // 第四步,对应的 mutation 被执行 countAdd () { // 第五步,在 mutation 里进行修改数据 this.state.count++ } },</code></pre> <p>注:mutation 内不建议写异步操作</p> <p><strong>传参进行修改</strong></p> <p>如果我们要修改的数据不是固定的,可以通过传参的方式进行修改</p> <pre><code class="language-vue"> const countAdd = () => { store.commit('countAdd', 10) } actions: { countAdd (store, num) { store.commit('countAdd', num) } }, mutations: { countAdd (state, num) { state.count += num } },</code></pre> 猜你想看 详解http和https的作用与区别 Vue计算属性及使用 TypechoCDN配置全过程 - 超详细 PHP变量常量定义以及使用 PHP数据类型 每日一学:PHP 中的array_flip函数详解 go使用DialTimeout实现TCP端口扫描 Goland的常用快捷键 Redis学习之安装Redis Linux 系统安装部署 Redis 完全指南 最后修改:2022 年 06 月 05 日 © 允许规范转载 赞 1 如果觉得我的文章对你有用,请随意赞赏