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

使用Cookie存储的Vuex页面刷新后丢失状态问题排查

Hey there, let's figure out why your Vuex state keeps disappearing after hitting F5 to refresh the page. I've worked through similar issues with vuex-persistedstate and js-cookie, so let's break down the possible causes and fixes step by step.

Your local IIS setup uses HTTP, right? The secure: true flag tells browsers to only store and send the cookie over HTTPS connections. In an HTTP environment like your local IIS, setting secure: true will make the browser ignore the cookie entirely—it won't even save it. That's likely a core issue, even though you said you toggled the value.

Make sure for local development, you set secure: false. For production (when you're using HTTPS), you can switch it back to true. A clean way to handle this is using environment variables to auto-toggle based on your environment:

secure: process.env.NODE_ENV === 'production'

Looking at your code, you're using Cookies.getJSON(key) for getItem, but this can fail silently if the cookie value isn't valid JSON (or if the cookie doesn't exist). Let's make the parsing more robust, and explicitly stringify the value when setting it to avoid ambiguity:

getItem: key => {
  const cookieValue = Cookies.get(key);
  try {
    // Return parsed state or empty object if cookie is missing/corrupted
    return cookieValue ? JSON.parse(cookieValue) : {};
  } catch (e) {
    console.error('Error parsing Vuex state cookie:', e);
    return {};
  }
},
setItem: (key, value) => Cookies.set(key, JSON.stringify(value), { 
  expires: 3, 
  secure: process.env.NODE_ENV === 'production'
}),

Before diving deeper, confirm the cookie exists in your browser:

  1. Open DevTools (F12)
  2. Go to the Application tab (Chrome) or Storage tab (Firefox)
  3. Expand Cookies and select your local IIS domain
  4. Look for the cookie matching your Vuex state key (default is vuex unless you set a custom key in createPersistedState)

If the cookie isn't there, the issue is definitely with the storage setup. If it is there, check its value to make sure it's the JSON representation of your state.

Rule Out Strict Mode Conflicts

Your store has strict: true enabled. While this is great for catching mutations outside of Vuex in development, sometimes it can clash with persistence plugins (though vuex-persistedstate should handle this). Try temporarily setting strict: false to see if that fixes the state loss. If it does, you can keep strict mode enabled but restrict it to development only:

strict: process.env.NODE_ENV !== 'production'

Optional: Specify Persisted Paths

By default, vuex-persistedstate saves your entire state, but if you only need specific modules persisted, you can define a paths array. This can help narrow down if a specific module is causing issues:

createPersistedState({
  // ... other config
  paths: ['module1', 'module2'] // Only persist these modules
})

Final Modified Code Example

Here's putting all these fixes together:

import * as Cookies from 'js-cookie';
import createPersistedState from 'vuex-persistedstate';
export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => {
          const cookieValue = Cookies.get(key);
          try {
            return cookieValue ? JSON.parse(cookieValue) : {};
          } catch (e) {
            console.error('Failed to parse Vuex state cookie:', e);
            return {};
          }
        },
        setItem: (key, value) => Cookies.set(key, JSON.stringify(value), { 
          expires: 3, 
          secure: process.env.NODE_ENV === 'production'
        }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ],
  actions,
  modules: {
    module1, module2, module3, module4, module5, module6, module7, module8, module9
  }
});

Give these steps a try—start with checking the secure flag and verifying the cookie exists, since those are the most common culprits in local HTTP environments.

内容的提问来源于stack exchange,提问作者user3084526

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:37:23