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

30c8f36844dedda17fa1552f3340e6da.png

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

const unsubscribe = store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})


// 你可以调用 unsubscribe 来停止订阅。
unsubscribe()

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

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

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

store.counter++


store.$patch({
  counter: store.counter + 1,
  name: 'Abalam',
})


store.$patch((state) => {
  state.items.push({ name: 'shoes', quantity: 1 })
  state.hasChanged = true
})

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

const unsubscribe = store.$subscribe((mutation, state) => {
  // import { MutationType } from 'pinia'
  mutation.type // 'direct' | 'patch object' | 'patch function'
  // 与 cartStore.$id 相同
  mutation.storeId // 'cart'
  // 仅适用于 mutation.type === 'patch object'
  mutation.payload // 补丁对象传递给 to cartStore.$patch()


  // 每当它发生变化时,将整个状态持久化到本地存储
  localStorage.setItem('cart', JSON.stringify(state))
})

订阅 Actions

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

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

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

const unsubscribe = store.$onAction(
  ({
    name, // action 的名字
    store, // store 实例
    args, // 调用这个 action 的参数
    after, // 在这个 action 执行完毕之后,执行这个函数
    onError, // 在这个 action 抛出异常的时候,执行这个函数
  }) => {
    // 记录开始的时间变量
    const startTime = Date.now()
    // 这将在 `store` 上的操作执行之前触发
    console.log(`Start "${name}" with params [${args.join(', ')}].`)


    // 如果 action 成功并且完全运行后,after 将触发。
    // 它将等待任何返回的 promise
    after((result) => {
      console.log(
        `Finished "${name}" after ${
          Date.now() - startTime
        }ms.\nResult: ${result}.`
      )
    })


    // 如果 action 抛出或返回 Promise.reject ,onError 将触发
    onError((error) => {
      console.warn(
        `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
      )
    })
  }
)


// 手动移除订阅
unsubscribe()

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值