※前提条件:vue3 的uniapp开发
每一个 Vuex 应用的核心就是 store(仓库),它包含着你的应用中大部分的状态 (state)。
状态管理有5个核心:state、getter、mutation、action、module。
单一状态树,定义应用状态的默认初始值,页面显示所需的数据从该对象中进行读取。
由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态: 注意:以下的代码,实际并不会使用,这里只作为讲解介绍使用
// 创建一个 Counter 组件 const Counter = { computed: { count () { return store.state.count } } }
每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
然而,这种模式导致组件依赖全局状态单例。在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):
通过属性访问,需要在根节点注入 store
import store from '@/store/index.js';//需要引入store export default { data() { return {} }, computed: { username() { return store.state.username } } }
在组件中使用,通过 this.$store 访问到 state 里的数据
export default { data() { return {} }, computed: { username() { return this.$store.state.username } } }
通过 mapState 辅助函数获取。
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。 为了解决这个问题,我们可以使用 mapState 辅助函数 帮助我们生成计算属性,让你少按几次键:
import { mapState } from 'vuex'//引入mapState export default { data() { return {} }, computed: mapState({ // 从state中拿到数据 箭头函数可使代码更简练 username: state => state.username, age: state => state.age, }) }
在 uni-app 项目根目录下,store 目录 index.js 文件下:
// 页面路径: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
<!-- 页面路径: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>
<!-- 页面路径: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>
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
<!-- 页面路径: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 辅助函数访问
通过属性访问,Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值。
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
<!-- 页面路径: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>
Vuex中store数据改变的唯一方法就是mutation
通俗的理解,mutations 里面装着改变数据的方法集合,处理数据逻辑的方法全部放在 mutations 里,使数据和视图分离。
Mutation 必须是同步函数 一条重要的原则就是要记住 mutation 必须是同步函数,我们要通过提交 mutation 的方式来改变状态数据,是因为我们想要更明确地追踪到状态的变化。
Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
// 页面路径: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)。
<!-- 页面路径: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 类似于 mutation ,不同在于:
注册一个简单的 action :
// 页面路径: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
<!-- 页面路径: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>
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
在 store 文件夹下新建 modules 文件夹,并在下面新建 moduleA.js 和 moduleB.js 文件用来存放 vuex 的 modules 模块
├── 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 | 全局变量 |
不能直接改变store里面的变量,由统一的方法修改数据 | 可以任意修改 |
每个组件可以根据自己vuex的变量名引用不受影响 | 全局变量可能操作命名污染 |
解决了多组件之间通信的问题 | 跨页面数据共享 |
适用于多模块、业务关系复杂的中大型项目 | 适用于demo或者小型项目 |
只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action 、mutation 和 getter 分割到单独的文件。
对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:
├── 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
Comment: