如何在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.
How to set cookie expiration in seconds or minutes?
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

