在vue3+pinia的项目中,组件中如何监听store的改变 - 掘金

在 Vue 3 和 Pinia 中,要在组件中监听 Store 中 state 的变化,可以使用 watch 或者 watchEffect 函数。下面是如何在 Vue 3 和 Pinia 中使用这两种方法的示例:

首先,假设你有一个 Pinia Store,如下所示:

javascript

复制代码

`import { defineStore } from 'pinia';
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});`

然后,在组件中,你可以使用 watchwatchEffect 监听 state 变化:

1. 使用 watch

xml

复制代码

`<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { watch } from 'vue';
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
const count = counterStore.$computed(() => counterStore.count);
const increment = () => counterStore.increment();
watch(count, (newValue, oldValue) => {
console.log('count changed from', oldValue, 'to', newValue);
});
return {
count,
increment
};
}
};
</script>`

2. 使用 watchEffect

xml

复制代码

`<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { watchEffect } from 'vue';
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
const count = counterStore.$computed(() => counterStore.count);
const increment = () => counterStore.increment();
watchEffect(() => {
console.log('count changed to', count.value);
});
return {
count,
increment
};
}
};
</script>`

这两种方法都可以用于在组件中监听 Store 中 state 的变化。watch 函数允许你访问新值和旧值,而 watchEffect 会在依赖的响应式对象发生变化时立即执行。根据你的需求选择合适的方法。


原网址: 访问
创建于: 2023-10-08 11:32:54
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论