【问题标题】:Is it possible to use $subscribe or watch inside the store itself?是否可以在商店内部使用 $subscribe 或 watch ?
【发布时间】:2022-10-31 06:33:07
【问题描述】:

每次商店的一部分发生变化时,我都想观看商店并进行新的 api 调用(使用商店操作)。如何在 (defineStore()) 存储本身内实现此观察程序?

【问题讨论】:

  • 你想通了吗?也有兴趣知道。谢谢
  • @jimmybondy 是的,看看这个:watch from inside a store? 在 github 中讨论。
  • 我已经看到了那个讨论,但从我的角度来看,它缺少一个完整的工作示例。我需要动作和吸气剂,但不知道如何将它们与设置商店一起使用。

标签: vue.js pinia


【解决方案1】:

如果您使用setup store,则可以使用此语法。这将只观察一个状态属性,然后根据该状态属性的变化触发副作用。

import { defineStore } from "pinia";
import { ref, watch } from "vue";

export const useCartStore = defineStore("cart", () => {
// state
  const items = ref([]);
  let cartIsEmpty  = ref(false)

// actions
function emptyCart() {
   *logic here to empty the cart*
   cartIsEmpty.value = true
  }

// watch
watch(cartIsEmpty, ()=>{
    if(cartIsEmpty.value === true){
      fetchItems()
    }
  })

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2020-03-26
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多