Pinia中使用Reactive定义数组,永久化存储及响应性的问题

发布时间:2024-03-22浏览次数:122 次
如题,在pinia中使用reactive或者shallowReactive定义的数组,或者对象中属性值为数组的属性,有时候会发现好像是丢失了响应性。其次,在pi

如题,在pinia中使用reactive或者shallowReactive定义的数组,或者对象中属性值为数组的属性,有时候会发现好像是丢失了响应性。其次,在pinia中使用pinia-plugin-persistedstate库做数据持久化方案时,会发现pinia中使用reactive定义的数组存储之后读取不到。

为了讲问题研究明白,我们专门安装了一个新的vue环境,然后一探究竟,以下是代码:

person.js的 store 文件代码:

import {defineStore} from "pinia";
import {reactive, ref, shallowReactive, shallowRef} from "vue";

export const usePersonStore = defineStore('person', () => {
    const detail = shallowReactive({
        name: "张三",
        age: 19,
        book: []
    })

    const hobby = shallowReactive([])

    const addHobby = () => {
        console.log('addHobby')
        hobby.push('看书')
    }

    const changeAge = () => {
        detail.age++
    }
    const addBook = () => {
        detail.book.push('水浒')
    }

    const num = ref(0)
    const add = () => {
        num.value++
    }

    return {detail, num, hobby, add, changeAge, addHobby, addBook}
}, {
    persist: {
        enabled: true,
        storage: localStorage
    }
})

main.js文件代码(即安装了pinia-plugin-persistedstate)

import {createApp} from 'vue'
import App from './App.vue'
import {createPinia} from "pinia";
import piniaPersist from 'pinia-plugin-persistedstate'

createApp(App).use(createPinia().use(piniaPersist)).mount('#app')

演示组件 APP.vue

<template>
    <h1>Pinia中使用Reactive定义数组,永久化存储及响应性的问题</h1>
    <hr/>
    <h2>{{ num }}</h2>
    <br/>
    <button @click="add">通过pinia修改num</button>
    <button @click="num++">通过调用组件修改num</button>

    <hr/>
    <h2>{{ detail }}</h2><br/>
    <button @click="changeAge">通过pinia修改age</button>
    <button @click="detail.age ++">通过调用组件修改age</button><br/><br/>
    <button @click="addBook">通过pinia添加一本书</button>
    <button @click="detail.book.push('红楼梦')">通过调用组件添加一本书</button>
    <br/><br/>

    <hr/>
    <h2>{{ hobby }}</h2><br/>
    <button @click="addHobby">通过pinia添加hobby</button>
    <button @click="hobby.push('学习')">通过调用组件添加hobby</button>
</template>

<script setup>
import {usePersonStore} from "./stores/person.js";

const personStore = usePersonStore()
import {storeToRefs} from "pinia";

const {num, detail, hobby} = storeToRefs(personStore)
const {add, changeAge, addHobby, addBook} = personStore
</script>

我们主要分不使用持久化和使用持久化两种情况进行测试,然后一次测试ref、shallowRef、reactive、shallowReactive这些定义的数组和对象中属性值为数组时的几种情形,因为测试过程较为繁琐,这里直接为大家分享我的测试结果:

针对以上结论,我们在pinia中使用reactive或者shallowReactive定义数组时,就需要小心一些了,因为可能会丢失响应性,如果你还需要对数据做持久化,那么在pinia中就要慎用reative了。

标签:
扫一扫,在手机上查看