当前位置:   article > 正文

$subscribe() 订阅状态及其变化

store.$subscribe

30c8f36844dedda17fa1552f3340e6da.png

可以通过 store 的 $subscribe() 方法查看状态及其变化。类似于 Vuex 的 subscribe 方法,订阅 store 的 mutation。

  1. const unsubscribe = store.subscribe((mutation, state) => {
  2. console.log(mutation.type)
  3. console.log(mutation.payload)
  4. })
  5. // 你可以调用 unsubscribe 来停止订阅。
  6. unsubscribe()

之前更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

  1. const store = new Vuex.Store({
  2. state: {
  3. count: 1
  4. },
  5. mutations: {
  6. increment (state) {
  7. // 变更状态
  8. state.count++
  9. }
  10. }
  11. })
  12. // 要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法
  13. store.commit('increment', 10)

现在更改 Pinia 的 store 中的状态不再需要自己去写 mutation 方法,除了直接用 store.counter++ 修改 store,你还可以调用 $patch 方法,$patch 方法也接受一个对象或者函数作为参数。

  1. store.counter++
  2. store.$patch({
  3. counter: store.counter + 1,
  4. name: 'Abalam',
  5. })
  6. store.$patch((state) => {
  7. state.items.push({ name: 'shoes', quantity: 1 })
  8. state.hasChanged = true
  9. })

所以默认 MutationType 有三种 'direct' | 'patch object' | 'patch function' 类型。

  1. const unsubscribe = store.$subscribe((mutation, state) => {
  2. // import { MutationType } from 'pinia'
  3. mutation.type // 'direct' | 'patch object' | 'patch function'
  4. // 与 cartStore.$id 相同
  5. mutation.storeId // 'cart'
  6. // 仅适用于 mutation.type === 'patch object'
  7. mutation.payload // 补丁对象传递给 to cartStore.$patch()
  8. // 每当它发生变化时,将整个状态持久化到本地存储
  9. localStorage.setItem('cart', JSON.stringify(state))
  10. })

订阅 Actions

可以使用 store.$onAction() 订阅 action 及其结果。传递给它的回调在 action 之前执行。

参数 after 处理 Promise 并允许您在 action 完成后执行函数。

onError 允许您在处理中抛出错误。这些对于在运行时跟踪错误很有用。

  1. const unsubscribe = store.$onAction(
  2. ({
  3. name, // action 的名字
  4. store, // store 实例
  5. args, // 调用这个 action 的参数
  6. after, // 在这个 action 执行完毕之后,执行这个函数
  7. onError, // 在这个 action 抛出异常的时候,执行这个函数
  8. }) => {
  9. // 记录开始的时间变量
  10. const startTime = Date.now()
  11. // 这将在 `store` 上的操作执行之前触发
  12. console.log(`Start "${name}" with params [${args.join(', ')}].`)
  13. // 如果 action 成功并且完全运行后,after 将触发。
  14. // 它将等待任何返回的 promise
  15. after((result) => {
  16. console.log(
  17. `Finished "${name}" after ${
  18. Date.now() - startTime
  19. }ms.\nResult: ${result}.`
  20. )
  21. })
  22. // 如果 action 抛出或返回 Promise.reject ,onError 将触发
  23. onError((error) => {
  24. console.warn(
  25. `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
  26. )
  27. })
  28. }
  29. )
  30. // 手动移除订阅
  31. unsubscribe()

默认情况下,action subscriptions 绑定到添加它们的组件(如果 store 位于组件的 setup() 内)。意思是,当组件被卸载时,它们将被自动删除。如果要在卸载组件后保留它们,请将 true 作为第二个参数传递给当前组件的 action subscription。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49859
推荐阅读
相关标签
  

闽ICP备14008679号