Observing state object in pinia does not trigger when object changes
P粉002546490
2023-08-28 12:14:33
<p>I have a deep object in my pinia state where I want to place an observer. </p>
<pre class="brush:js;toolbar:false;">export const useProductStore = defineStore("product", {
state: () => ({
attributes: {},
}),
});
</pre>
<p>When an object has data inside it, it looks like this: </p>
<pre class="brush:json;toolbar:false;">attributes: {
english: {
0: {
key: "key1",
value: "value1"
},
1: {
key: "key2",
value: "value2"
},
...
}
}
</pre>
<p>I'm trying to place an observer on this object, but when the value changes, the observer doesn't fire. This is the component I'm trying to do this in: </p>
<pre class="brush:js;toolbar:false;"><script setup>
import { useProductStore } from "@/stores/ProductStore";
import { storeToRefs } from "pinia";
const productStore = useProductStore();
const { attributes } = storeToRefs(productStore);
watch(() => ({...attributes}), (newValue, oldValue) => {
console.log(oldValue);
console.log(newValue);
}, { deep: true });
</script>
</pre>
<p>This comes directly from the pinia documentation, but when I change the state, nothing happens. Using vue dev tools I can see the state object is changing so I know it's reactive. What did I miss? </p>
storeToRefs
Generateref()代码>
s.You say this example "comes directly from the pinia documentation", but I doubt you found
ref
propagated anywhere in the pinia documentation. If you do this, then this is a bug and should be pointed out to posva by raising an issue onpinia
's repository.You can watch it directly for reference:
...or you can use an arrow function to view its
.value
1:Note that the
newVal
andoldVal
parameters are Agent 2. To access its target, use toRaw.Working Demonstration. p>
1 - It allows for narrower observers, for example:
2 - If you put an object into
ref()
" the object is related toreactive( )
" Perform deep reactions (see Details). Also readReactive Proxy vs. Raw Proxy .