如何让 pinia 与 vue3 中的嵌套对象一起工作

eps*_*lbe 10 vuejs3 pinia

如何获得更新嵌套属性的反应式组件:

我有一个 pinia 商店定义如下

import { defineStore } from "pinia"
export const useStore = defineStore({
    id: "poc",
    state: () => ({ str: "", nested: { obj: "" } }),
    persist: {
        enabled: true,
        strategies: [{ storage: localStorage }],
    },
})
Run Code Online (Sandbox Code Playgroud)

以及以下 vue3 组件

<script lang="ts">
import { ref } from "vue"
import { storeToRefs } from "pinia"
import { useStore } from "./store"
export default {
    setup() {
        const store = useStore()
        const example = storeToRefs(store)

        const mStr = ref(example.str)
        const mObj = ref(example.nested.value.obj) // <--- this is where I believe the problem is
        store.str = mStr.value
        store.nested.obj = mObj.value

        return { mObj, mStr, store }
    },
}
</script>

<template>
    <h1>PoC</h1>
    <input v-model="mObj" placeholder="obj" />
    <input v-model="mStr" placeholder="str" />
</template>
Run Code Online (Sandbox Code Playgroud)

当我更新 str 字段时,它按预期工作,但对于嵌套对象,它不会。我怀疑我在打电话时失去了反应性nested.value,也就是说 - 我不知道如何使其反应性。

eps*_*lbe 1

多一点挖掘和https://github.com/vuejs/pinia/discussions/854最终让我足以自己想出一个(更优雅的)解决方案。

<script lang="ts">
import { useStore } from "./store"
export default {
    setup() {
        const store = useStore()
        return { store }
    },
}
</script>

<template>
    <h1>test</h1>
    <input v-model="store.str" placeholder="obj" />
    <input v-model="store.nested.obj" placeholder="str" />
</template>
Run Code Online (Sandbox Code Playgroud)