赞
踩

可以通过 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))
- })
可以使用 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。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。