vue实现设置永久时间
使用 localStorage 存储时间
在 Vue 中,可以通过 localStorage 来存储时间数据,实现永久保存。localStorage 是浏览器提供的本地存储机制,数据不会随着页面刷新或关闭而丢失。
// 存储时间
localStorage.setItem('permanentTime', new Date().toISOString());
// 获取时间
const savedTime = localStorage.getItem('permanentTime');
console.log(new Date(savedTime));
使用 Vuex 持久化插件
如果需要结合 Vuex 管理状态,可以使用 vuex-persistedstate 插件将 Vuex 的状态持久化到 localStorage 或 sessionStorage 中。
安装插件:
npm install vuex-persistedstate
配置 Vuex:
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
key: 'vuex',
paths: ['time'] // 只持久化 time 状态
})]
})
使用 Cookies 存储时间
Cookies 也可以实现永久存储,但需要注意设置过期时间。
// 设置 cookie,过期时间设置为 10 年后
document.cookie = `permanentTime=${new Date().toISOString()}; expires=${new Date(Date.now() + 10 * 365 * 24 * 60 * 60 * 1000).toUTCString()}; path=/`;
// 读取 cookie
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
const timeCookie = getCookie('permanentTime');
结合 Vue 组件实现
在 Vue 组件中,可以结合以上方法实现时间的永久存储和读取。
export default {
data() {
return {
permanentTime: null
}
},
created() {
// 尝试从 localStorage 读取
const savedTime = localStorage.getItem('permanentTime');
if (savedTime) {
this.permanentTime = new Date(savedTime);
} else {
// 如果没有存储过,设置当前时间并保存
this.permanentTime = new Date();
localStorage.setItem('permanentTime', this.permanentTime.toISOString());
}
},
methods: {
updateTime() {
this.permanentTime = new Date();
localStorage.setItem('permanentTime', this.permanentTime.toISOString());
}
}
}
使用 IndexedDB 存储大量时间数据
如果需要存储大量时间数据或需要更复杂的查询,可以使用 IndexedDB。
// 打开或创建数据库
const request = indexedDB.open('TimeDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('times')) {
db.createObjectStore('times', { keyPath: 'id', autoIncrement: true });
}
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['times'], 'readwrite');
const store = transaction.objectStore('times');
// 添加时间记录
store.add({ time: new Date() });
// 获取所有时间记录
const getAll = store.getAll();
getAll.onsuccess = () => {
console.log(getAll.result);
};
};
注意事项
浏览器存储都有大小限制,localStorage 通常为 5MB,cookies 约 4KB,IndexedDB 则更大。根据实际需求选择合适的存储方式。
敏感时间数据不应仅依赖前端存储,应考虑后端数据库进行持久化,前端只作为缓存或临时存储使用。
跨域情况下,存储访问可能受限,需要特别注意同源策略限制。







