You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:53:18