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

如何在Cookie与Vue-persist中设置小时/分钟级Cookie过期时间?

Hey there! Let's unpack your questions about the VuexPersist cookie configuration clearly:

What does expires: 3 mean?

When using the js-cookie library (which your Cookies.set call relies on), passing a number to the expires option sets the cookie's expiration in days. So expires: 3 means your persisted Vuex user module data will be stored in a cookie that automatically expires 3 full days after it's created.

The expires option also accepts a Date object, which lets you set precise expiration times down to seconds or minutes. Instead of passing a raw number, you'll calculate a future date by adding your desired time interval to the current time, then pass that date to Cookies.set.

Here's how to adjust your VuexPersist configuration for different short-term timeframes:

Example 1: Expire after 30 seconds

const vuexCookie = new VuexPersist({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) => {
    const expireDate = new Date();
    expireDate.setSeconds(expireDate.getSeconds() + 30); // Add 30 seconds to current time
    Cookies.set(key, state, { expires: expireDate });
  },
  modules: ['user'] // only save user module
})

Example 2: Expire after 10 minutes

const vuexCookie = new VuexPersist({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) => {
    const expireDate = new Date();
    expireDate.setMinutes(expireDate.getMinutes() + 10); // Add 10 minutes to current time
    Cookies.set(key, state, { expires: expireDate });
  },
  modules: ['user'] // only save user module
})

Just note: when using a Date object, double-check that you're calculating the future time correctly relative to the current date/time. This approach gives you full control over the cookie's lifespan beyond just day-long intervals.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:36:59