最近自己在敲一些 demo 的时候涉及到一些数据的存储,因为项目不大,也懒得再启一个后端服务和数据库了,就思考能不能纯前端实现一种比较直观友好的存储数据的方式。首先想到的肯定就是 localStorage,但是原生API使用起来比较冗长,有些累,就想着找一种简单方便的方式。
由于项目是使用 Vue3 进行开发,所以就去看了 VueUse 中的 useStorage,看完后就想着将其与 Pinia 结合使用岂不是很妙。
下面是我使用这种方式模拟一个常规的增删改查操作。
store.js
import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';
export const useTbReportStore = defineStore('tbReport', {
state: () => ({
reports: useStorage('tb-report', []),
}),
getters: {
getReports: (state) => state.reports,
},
actions: {
create(data) {
this.reports.push(data);
},
update(data) {
const { id, name, remark } = data;
this.reports.forEach((item) => {
if (item.id === id) {
item.name = name;
item.remark = remark;
}
});
},
findOne(id) {
return this.reports.find((item) => item.id === id) || null;
},
remove(id) {
this.reports = this.reports.filter((item) => item.id !== id);
},
},
});
在 js 和 vue 文件中就可以这样方便的使用
import { useTbReportStore } from './store.js';
const tbReportStore = useTbReportStore();
// 新增
tbReportStore.create(data)
// 查询一条
const res = tbReportStore.findOne(id)
...
因为 useStorage 将本地存储的操作变为了响应式的方式,在Vue3项目中使用起来就极为方便,再结合 Pinia 状态管理一起使用,跨组件操作也更加的方便。数据也能持久化存储在本地。
这种方式代码写起来幸福感满满的。