如何在Pinia的Setup Store中调用其他Getter及传参?
Pinia Setup Store 相关问题解答
问题1:如何在Setup Store中使用其他Getter?
在Pinia的Setup Store写法里,所有用computed定义的Getter都是普通的响应式变量,直接通过.value访问就能在另一个Getter里使用。修改你的示例代码如下:
export const useCounterStore = defineStore('counter', () => { const count = ref(0) const name = ref('Eduardo') const doubleCount = computed(() => count.value * 2) // 直接访问doubleCount.value即可使用这个Getter的结果 const HOW_TO_USE = computed(() => `当前计数的两倍是:${doubleCount.value}`) function increment() { count.value++ } return { count, name, doubleCount, HOW_TO_USE, increment } })
问题2:给Getter传参应该用哪种写法?
computed本身不支持直接接收参数,所以第一种写法是无效的。正确的写法是定义一个返回computed的函数,也就是你给出的第二种写法,这样就能通过函数接收参数,再在内部的computed逻辑里使用。
错误写法(无效)
// computed的回调函数无法接收参数,这种写法不生效 const HOW_TO_USE = computed((arg)=> /* do with arg */)
正确写法
// 定义一个接收参数的函数,内部返回computed const HOW_TO_USE = (arg) => computed(() => { // 这里可以使用传入的arg和其他响应式变量 return `传入的参数是${arg},当前计数两倍是${doubleCount.value}` })
在组件中使用时,需要先调用这个函数传入参数,再访问.value:
const store = useCounterStore() // 传入参数后获取响应式结果 const result = store.HOW_TO_USE('测试参数').value
内容的提问来源于stack exchange,提问作者wildfluss
相关产品推荐
相关产品推荐

