在 Vue 3 和 Pinia 中,要在组件中监听 Store 中 state 的变化,可以使用 watch 或者 watchEffect 函数。下面是如何在 Vue 3 和 Pinia 中使用这两种方法的示例:
首先,假设你有一个 Pinia Store,如下所示:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
然后,在组件中,你可以使用 watch 或 watchEffect 监听 state 变化:
1. 使用 watch:
<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:
<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 会在依赖的响应式对象发生变化时立即执行。根据你的需求选择合适的方法。