Vue 3选项式API结合Pinia如何实现HMR热更新?
Pinia选项式仓库实现HMR热更新方案
直接在Store文件里加热更新逻辑就行
你之前在组件里处理HMR是找错地方了,Pinia的HMR必须在Store定义的文件内配置。调整你的Store代码如下:
import { defineStore } from 'pinia' // 用命名导出定义并导出store,更方便HMR识别 export const useUserStore = defineStore('user', { state: () => ({ authState: false, }) }) // 在文件末尾添加HMR处理代码 if (import.meta.hot) { import.meta.hot.accept(import.meta.hot, (newModule) => { // 模块更新时,用新的store配置覆盖旧的 if (newModule?.useUserStore) { useUserStore().$hotUpdate(newModule.useUserStore.options) } }) }
组件里正常导入使用即可
在Application.vue里直接导入命名导出的store就行,不需要额外处理:
import { useUserStore } from '@/stores/user'
要是你坚持用默认导出也可以
如果不想改导出方式,就用下面的写法:
import { defineStore } from 'pinia' const userStore = defineStore('user', { state: () => ({ authState: false, }) }) export default userStore if (import.meta.hot) { import.meta.hot.accept(import.meta.hot, (newModule) => { if (newModule.default) { userStore().$hotUpdate(newModule.default.options) } }) }
核心逻辑:Pinia的HMR依赖调用$hotUpdate方法传入新的store配置来实现状态、方法的热更新,所有处理必须放在Store定义文件内,组件里不需要额外操作。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

