做a 视频在线观看网站,中国有色金属价格网,不用编程做APP和响应式网站,广州网站建设网站开发一、前言
测试提出#xff0c;登出登录后#xff0c;再次进入页面后。页面的查询项非初始状态。检查后发现#xff0c;是因为查询项的值存到了store呢#xff0c;从store中获取#xff0c;故需要一个重置store的方法
二、pinia
查阅pinia官网后#xff0c;发现pinia提…一、前言
测试提出登出登录后再次进入页面后。页面的查询项非初始状态。检查后发现是因为查询项的值存到了store呢从store中获取故需要一个重置store的方法
二、pinia
查阅pinia官网后发现pinia提供了一个reset方法可以重置状态。官网位置重置状态
重置状态
您可以通过调用 store 上的 $reset() 方法将状态 reset 到其初始值
const store useStore()store.$reset()但是实操发现直接调用报错 pinia.js?v0f025a7f:1058 Uncaught (in promise) Error: : Store data is built using the setup syntax and does not implement $reset(). at Proxy.$reset (pinia.js?v0f025a7f:1058:13) 原因Pinia 提供的 $reset 方法仅适用于使用 options 语法即 state 选项定义的 store对于使用 setup 语法定义的 store不适用需要手动实现状态重置功能。
三、解决方案
手动赋值每个状态不优雅故考虑使用pinia的插件为pinia扩展一个reset方法
创建pinia插件
// src/store/plugins/piniaResetPlugin.js
export function createResetPlugin() {return ({ store }) {// 保存初始状态的副本const initialState JSON.parse(JSON.stringify(store.$state))// 定义 reset 方法store.$reset () {store.$patch(initialState)}}
}注册pinia插件
// src/main.js
import { createApp } from vue
import { createPinia } from pinia
import App from ./App.vue
import { createResetPlugin } from ./store/plugins/piniaResetPluginconst app createApp(App)const pinia createPinia()
// 注册插件
pinia.use(createResetPlugin())app.use(pinia)
app.mount(#app)使用$reset方法
templatebutton clickhandleLogoutLogout/button
/templatescript
import { useDataStore } from /store/interface/data
import { useAuthStore } from /store/auth // 假设有一个 auth store 用于处理登录export default {setup() {const dataStore useDataStore()const authStore useAuthStore()const handleLogout async () {await authStore.logout()// 调用 reset 方法dataStore.$reset()// 其他登出逻辑this.$router.push(/login) // 例如重定向到登录页}return {handleLogout}}
}
/script一个完整的插件开发注册使用的流程就完成啦
四、总结
通过创建一个适用于 setup 语法的 Pinia 插件可以更优雅地为所有 stores 添加 reset 方法。这种方法确保状态重置功能在 setup 语法的 store 中也能正常工作。