#author("2022-12-15T11:04:00+08:00","default:Admin","Admin") #author("2022-12-15T11:09:00+08:00","default:Admin","Admin") [[Vue]] &color(red){※前提条件:vue3 的uniapp开发}; #contents * 概要 [#ee353b9e] 每一个 Vuex 应用的核心就是 store(仓库),它包含着你的应用中大部分的状态 (state)。 状态管理有5个核心:state、getter、mutation、action、module。 ** state [#e5ad3791] 单一状态树,定义应用状态的默认初始值,页面显示所需的数据从该对象中进行读取。 - Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。它便作为一个“唯一数据源”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。 - 单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。 - 不可直接对 state 进行更改,需要通过 Mutation 方法来更改。 由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态: &color(red){注意:以下的代码,实际并不会使用,这里只作为讲解介绍使用}; #codeprettify{{ // 创建一个 Counter 组件 const Counter = { computed: { count () { return store.state.count } } } }} 每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。 然而,这种模式导致组件依赖全局状态单例。在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。 Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)): *** 获取state [#z4a14fd2] **** 通过属性访问 [#ffe22e82] 通过属性访问,需要在根节点注入 store #codeprettify{{ import store from '@/store/index.js';//需要引入store export default { data() { return {} }, computed: { username() { return store.state.username } } } }} **** 在组件中使用 [#s480e30e] 在组件中使用,通过 this.$store 访问到 state 里的数据 #codeprettify{{ export default { data() { return {} }, computed: { username() { return this.$store.state.username } } } }} **** mapState [#y1e7609f] 通过 mapState 辅助函数获取。 当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。 为了解决这个问题,我们可以使用 mapState 辅助函数 帮助我们生成计算属性,让你少按几次键: #codeprettify{{ import { mapState } from 'vuex'//引入mapState export default { data() { return {} }, computed: mapState({ // 从state中拿到数据 箭头函数可使代码更简练 username: state => state.username, age: state => state.age, }) } }} ** Getter [#na7c9a4a] 在 uni-app 项目根目录下,store 目录 index.js 文件下: #codeprettify{{ // 页面路径:store/index.js import { createStore } from 'vuex' const store = createStore({ state: { todos: [{ id: 1, text: '我是内容一', done: true }, { id: 2, text: '我是内容二', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } }) export default store }} *** 获取getters [#m78d5ff4] **** 通过属性访问 [#n648acec] #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view v-for="(item,index) in todos"> <view>\{\{item.id\}\}</view> <view>\{\{item.text\}\}</view> <view>\{\{item.done\}\}</view> </view> </view> </template> <script> import store from '@/store/index.js'//需要引入store export default { computed: { todos() { return store.getters.doneTodos } } } </script> }} **** 通过 this.$store 访问 [#xa4f48ed] #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view v-for="(item,index) in todos"> <view>\{\{item.id\}\}</view> <view>\{\{item.text\}\}</view> <view>\{\{item.done\}\}</view> </view> </view> </template> <script> export default { computed: { todos() { return this.$store.getters.doneTodos } } } </script> }} **** 通过方法访问 [#lbc26ff2] 你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。 注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。 #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view v-for="(item,index) in todos"> <view>\{\{item\}\}</view> </view> </view> </template> <script> export default { computed: { todos() { return this.$store.getters.getTodoById(2) } } } </script> }} **** mapGetters [#k2109d57] 通过 mapGetters 辅助函数访问 通过属性访问,Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值。 mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性: #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view>\{\{doneTodosCount\}\}</view> </view> </template> <script> import {mapGetters} from 'vuex' //引入mapGetters export default { computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodos', 'doneTodosCount', // ... ]) } } </script> }} ** Mutation [#o1717086] Vuex中store数据改变的唯一方法就是mutation 通俗的理解,mutations 里面装着改变数据的方法集合,处理数据逻辑的方法全部放在 mutations 里,使数据和视图分离。 具体请参考 [[+Vue+mutations]] &color(red){Mutation 必须是同步函数}; 一条重要的原则就是要记住 mutation 必须是同步函数,我们要通过提交 mutation 的方式来改变状态数据,是因为我们想要更明确地追踪到状态的变化。 &color(red){Vuex 中的 mutation 非常类似于事件};:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数: #codeprettify{{ // 页面路径:store/index.js import { createStore } from 'vuex' const store = createStore({ state: { count: 1 }, mutations: { add(state) { // 变更状态 state.count += 2 } } }) export default store }} 你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 add 的 mutation 时,调用此函数”,要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法。 注意:store.commit 调用 mutation(需要在根节点注入 store)。 #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view>数量:\{\{count\}\}</view> <button @click="addCount">增加</button> </view> </template> <script> import store from '@/store/index.js' export default { computed: { count() { return this.$store.state.count } }, methods: { addCount() { store.commit('add') } } } </script> }} ** Action [#n2dd8cbc] action 类似于 mutation ,不同在于: - action 提交的是 mutation,通过 mutation 来改变 state ,而不是直接变更状态。 - action 可以包含任意异步操作。 注册一个简单的 action : #codeprettify{{ // 页面路径:store/index.js import { createStore } from 'vuex' const store = createStore({ state: { count: 1 }, mutations:{ add(state) { // 变更状态 state.count += 2 } }, actions:{ addCountAction (context) { context.commit('add') } } }) export default store }} *** 分发 Action [#f9d87645] #codeprettify{{ <!-- 页面路径:pages/index/index.vue --> <template> <view> <view>数量:\{\{count\}\}</view> <button @click="add">增加</button> </view> </template> <script> import store from '@/store/index.js'; export default { computed: { count() { return this.$store.state.count } }, methods: { add () { //actions 通过 store.dispatch 方法触发。 store.dispatch('addCountAction') //actions 支持以载荷形式分发 context.commit('add',payload) // 以载荷形式分发 store.dispatch('addCountAction', {amount: 10}) } } } </script> }} ** Module [#n680a1b5] 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割: 在 store 文件夹下新建 modules 文件夹,并在下面新建 moduleA.js 和 moduleB.js 文件用来存放 vuex 的 modules 模块 #codeprettify{{ ├── components # 组件文件夹 └── myButton └── myButton.vue # myButton组件 ├── pages └── index └── index.vue # index页面 ├── static ├── store ├── index.js # 我们组装模块并导出 store 的地方 └── modules # 模块文件夹 ├── moduleA.js # 模块moduleA └── moduleB.js # 模块moduleB ├── App.vue ├── main.js ├── manifest.json ├── pages.json └── uni.scss }} * vuex与全局变量区别 [#q80b869d] |vuex|全局变量|h |不能直接改变store里面的变量,由统一的方法修改数据|可以任意修改| |每个组件可以根据自己vuex的变量名引用不受影响|全局变量可能操作命名污染| |解决了多组件之间通信的问题|跨页面数据共享| |适用于多模块、业务关系复杂的中大型项目|适用于demo或者小型项目| * 什么时候需要用vuex [#w22ea6f7] - 当一个组件需要多次派发事件时。例如购物车数量加减。 - 跨组件共享数据、跨页面共享数据。例如订单状态更新。 - 需要持久化的数据。例如登录后用户的信息。 - 当您需要开发中大型应用,适合复杂的多模块多页面的数据交互,考虑如何更好地在组件外部管理状态时。 * 使用 Vuex 需要遵守的规则 [#j5be9b8c] - 应用层级的状态应该集中到单个 store 对象中。 - 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。 - 异步逻辑都应该封装到 action 里面。 只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action 、mutation 和 getter 分割到单独的文件。 对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例: #codeprettify{{ ├── pages ├── static └── store ├── index.js # 我们组装模块并导出 store 的地方 ├── actions.js # 根级别的 action ├── mutations.js # 根级别的 mutation └── modules # 模块文件夹 ├── cart.js # 购物车模块 └── products.js # 产品模块 ├── App.vue ├── main.js ├── manifest.json ├── pages.json └── uni.scss }} #hr(); Comment: #comment_kcaptcha