【Vue3学习】Vuex 状态管理 store

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

安装

npm

npm install vuex@next --save

yarn

npm install vuex@next --save

基本使用

1)创建文件src/store/index.js,内容如下:

import {
    
     createStore } from 'vuex'

// 创建一个新的 store 实例
export default createStore({
    
    
  state:  {
    
    
      count: 0
  },
  getters:{
    
    
    evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
  },
  mutations: {
    
    
    increment (state, n) {
    
    
      state.count+=n
    }
  },
  actions: {
    
    
    increment(context,n){
    
    
      context.commit('increment',n)
    }
  }
})

2)在main.js中引入store/index.js

import App from './App.vue'
// 引入store
import store from './store';

const app = createApp(App)
// 使用store //
app.use(store)

3)在组件中使用

<template>
  
  <div>
    <h3>Count demo</h3>
    useStore:{
    
    {
    
     count }} 
    <button @click="increment()">increment</button>
    <div>evenOrOdd:{
    
    {
    
     evenOrOdd }}</div>
    <button @click="addByAction()">addByAction</button>
    <button @click="addPromise()">incrementPromise</button>
  </div>
  
</template>

<script setup>

import {
    
     computed } from 'vue'
import {
    
     useStore  } from 'vuex'
// 通过useStore得到store对象
const store = useStore()
// 通过计算属性得到state.count
const count = computed(()=> store.state.count)
function increment(){
    
    
  // 提交commit,调用Mutation中的increment方法
  store.commit('increment',1)
}
// 通过计算属性得到getters.evenOrOdd
const evenOrOdd = computed(()=>store.getters.evenOrOdd)
// 分发action,触发方法increment
function addByAction(){
    
    
  store.dispatch('increment',1)
}
</script>

4)运行工程,界面如下

在这里插入图片描述

核心概念

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
image

1、State

单一状态树

Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT)”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。

mapState 辅助函数

使用 mapState 辅助函数帮助我们生成计算属性

// 在单独构建的版本中辅助函数为 Vuex.mapState
import {
    
     mapState } from 'vuex'

export default {
    
    
  // ...
  computed: mapState({
    
    
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
    
    
      return state.count + this.localCount
    }
  })
}

数组

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

对象展开运算符

computed: {
    
    
  localComputed () {
    
     /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    
    
    // ...
  })
}

注意,mapState等辅助函数不能再组合式api<script setup>中使用

2、Getter

Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)
Getter 接受 state 作为其第一个参数:

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)
    }
  }
})

通过属性访问

Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作为第二个参数:

getters: {
    
    
  // ...
  doneTodosCount (state, getters) {
    
    
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1

注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

通过方法访问

你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

getters: {
    
    
  // ...
  getTodoById: (state) => (id) => {
    
    
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

mapGetters 辅助函数

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

import {
    
     mapGetters } from 'vuex'

export default {
    
    
  // ...
  computed: {
    
    
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

如果你想将一个 getter 属性另取一个名字,使用对象形式:

import {
    
     mapGetters } from 'vuex'

export default {
    
    
  // ...
  computed: {
    
    
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

3、Mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

const store = createStore({
    
    
  state: {
    
    
    count: 1
  },
  mutations: {
    
    
    increment (state) {
    
    
      // 变更状态
      state.count++
    }
  }
})

提交mutation

store.commit('increment')

你可以向 store.commit 传入额外的参数,即 mutation 的载荷(payload)

// ...
mutations: {
    
    
  increment (state, n) {
    
    
    state.count += n
  }
}
store.commit('increment', 10)

对象风格的提交方式

提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

store.commit({
    
    
  type: 'increment',
  amount: 10
})

当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此处理函数保持不变:

mutations: {
    
    
  increment (state, payload) {
    
    
    state.count += payload.amount
  }
}

在 mutation 中混合异步调用会导致你的程序很难调试。例如,当你调用了两个包含异步回调的 mutation 来改变状态,你怎么知道什么时候回调和哪个先回调呢?这就是为什么我们要区分这两个概念。在 Vuex 中,mutation 都是同步事务

mapMutations 辅助函数

import {
    
     mapMutations } from 'vuex'

export default {
    
    
  // ...
  methods: {
    
    
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
    
    
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

4、Action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
const store = createStore({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment (state) {
    
    
      state.count++
    }
  },
  actions: {
    
    
    increment (context) {
    
    
      context.commit('increment')
    }
  }
})

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

实践中,我们会经常用到 ES2015 的参数解构来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
    
    
  increment ({
     
      commit }) {
    
    
    commit('increment')
  }
}

分发 Action

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

actions: {
    
    
  incrementAsync ({
     
      commit }) {
    
    
    setTimeout(() => {
    
    
      commit('increment')
    }, 1000)
  }
}

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
    
    
  amount: 10
})

// 以对象形式分发
store.dispatch({
    
    
  type: 'incrementAsync',
  amount: 10
})

来看一个更加实际的购物车示例,涉及到调用异步 API 和分发多重 mutation:

actions: {
    
    
  checkout ({
     
      commit, state }, products) {
    
    
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求
    // 然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)。

5、Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
    
    
  state: () => ({
    
     ... }),
  mutations: {
    
     ... },
  actions: {
    
     ... },
  getters: {
    
     ... }
}

const moduleB = {
    
    
  state: () => ({
    
     ... }),
  mutations: {
    
     ... },
  actions: {
    
     ... }
}

const store = createStore({
    
    
  modules: {
    
    
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

命名空间

默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间的——这样使得多个模块能够对同一个 action 或 mutation 作出响应。

如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:

const store = createStore({
    
    
  modules: {
    
    
    account: {
    
    
      namespaced: true,
      // 模块内容(module assets)
      state: () => ({
    
     ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
    
    
        isAdmin () {
    
     ... } // -> getters['account/isAdmin']
      },
      actions: {
    
    
        login () {
    
     ... } // -> dispatch('account/login')
      },
      mutations: {
    
    
        login () {
    
     ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
    
    
        // 继承父模块的命名空间
        myPage: {
    
    
          state: () => ({
    
     ... }),
          getters: {
    
    
            profile () {
    
     ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
    
    
          namespaced: true,
          state: () => ({
    
     ... }),
          getters: {
    
    
            popular () {
    
     ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

带命名空间的绑定函数

当使用 mapState、mapGetters、mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:

computed: {
    
    
  ...mapState({
    
    
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  }),
  ...mapGetters([
    'some/nested/module/someGetter', // -> this['some/nested/module/someGetter']
    'some/nested/module/someOtherGetter', // -> this['some/nested/module/someOtherGetter']
  ])
},
methods: {
    
    
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:

computed: {
    
    
  ...mapState('some/nested/module', {
    
    
    a: state => state.a,
    b: state => state.b
  }),
  ...mapGetters('some/nested/module', [
    'someGetter', // -> this.someGetter
    'someOtherGetter', // -> this.someOtherGetter
  ])
},
methods: {
    
    
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

import {
    
     createNamespacedHelpers } from 'vuex'

const {
    
     mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
    
    
  computed: {
    
    
    // 在 `some/nested/module` 中查找
    ...mapState({
    
    
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    
    
    // 在 `some/nested/module` 中查找
    ...mapActions([
      'foo',
      'bar'
    ])
  }
}

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

import {
    
     createStore } from 'vuex'

const store = createStore({
    
     /* 选项 */ })

// 注册模块 `myModule`
store.registerModule('myModule', {
    
    
  // ...
})

// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
    
    
  // ...
})

你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。

注意,你可以通过 store.hasModule(moduleName) 方法检查该模块是否已经被注册到 store。需要记住的是,嵌套模块应该以数组形式传递给 registerModule 和 hasModule,而不是以路径字符串的形式传递给 module。

参考

  • https://vuex.vuejs.org/zh/

猜你喜欢

转载自blog.csdn.net/wlddhj/article/details/131257203