Observing state object in pinia does not trigger when object changes
P粉002546490
P粉002546490 2023-08-28 12:14:33
0
1
579
<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>
P粉002546490
P粉002546490

reply all(1)
P粉668113768

storeToRefs Generate ref()代码>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 on pinia's repository.

You can watch it directly for reference:

watch(
  attributes,
  handler, 
  { deep: true }
)

...or you can use an arrow function to view its .value1:

watch(
  () => attributes.value,
  handler,
  { deep: true }
)

Note that the newVal and oldVal parameters are Agent 2. To access its target, use toRaw.

Working Demonstration. p>


1 - It allows for narrower observers, for example:

watch(
  () => attributes.value[0]?.value),
  handler
)

2 - If you put an object into ref() " the object is related to reactive( )" Perform deep reactions (see Details). Also readReactive Proxy vs. Raw Proxy .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template