欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > pinia在setup语法下使用$reset()报错的解决方法

pinia在setup语法下使用$reset()报错的解决方法

2025/5/21 20:14:41 来源:https://blog.csdn.net/qq176243970/article/details/148058750  浏览:    关键词:pinia在setup语法下使用$reset()报错的解决方法

Store "xxx" is built using the setup syntax and does not implement $reset().
自定义实现 $reset() 方法

main.ts

...
// 引入数仓
import pinia from '@/store'
const app = createApp(App)pinia.use(({ store }) => {// store.$state 是一个对象(即引用数据类型)没有效果, 需要使用JSON.parse()和JSON.stringify()进行深拷贝// 获取初始状态, 用于重置store(深拷贝后initialState与最初的store.$state值没有任何关系了)const initialState = JSON.parse(JSON.stringify(store.$state));// 给store添加$reset()方法store.$reset = () => {// 第一次之后的重置也存在引用型数据, 需要使用JSON.parse()和JSON.stringify()进行深拷贝//store.$patch(JSON.parse(JSON.stringify(initialState))); //更新store数据,也可以使用此方法store.$state = JSON.parse(JSON.stringify(initialState));};
})
app.use(pinia)
app.mount('#app')
...

store/test.ts

import { ref } from 'vue'
import { defineStore } from 'pinia'
export default defineStore('userStore', () => {const nick = ref<string>('小明')const codes = ref<number[]>([80])return { nick, codes }
})

views/user/index.vue

<template><div class="home"><h4>用户信息表单:</h4><div>昵称:<input type="text" v-model="nick" /></div><div>得分:{{codes}}</div></div><button type="button" @click="gaibian">修改</button><button type="button" @click="userStore.$reset()">重置</button>
</template><script setup lang="ts">
import useUserStore from '@/store/test'
import { toRefs } from 'vue'
const userStore = useUserStore()
const { nick, codes } = toRefs(userStore)function gaibian() {userStore.$patch(state => {state.nick = '小红'state.codes.push(100)})
}</script><style lang="scss" scoped></style>

参考地址:https://www.bilibili.com/opus/711566559457312801

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词