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

14 阅读1分钟

异常: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>

参考地址:www.bilibili.com/opus/711566…