Files
YG_FT/frontend/src/stores/tools.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import type { CustomTool } from '@/types'
/**
* storelocalStorage
* web customTools
*/
export const useToolsStore = defineStore('tools', () => {
const STORAGE_KEY = 'customTools'
const tools = ref<CustomTool[]>(loadFromStorage())
function loadFromStorage(): CustomTool[] {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
} catch {
return []
}
}
// 持久化
watch(
tools,
(val) => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(val))
},
{ deep: true },
)
function addTool(tool: CustomTool) {
tools.value.push(tool)
}
function updateTool(id: string, data: Partial<CustomTool>) {
const idx = tools.value.findIndex((t) => t.id === id)
if (idx !== -1) tools.value[idx] = { ...tools.value[idx], ...data }
}
function removeTool(id: string) {
tools.value = tools.value.filter((t) => t.id !== id)
}
function getTool(id: string): CustomTool | undefined {
return tools.value.find((t) => t.id === id)
}
return { tools, addTool, updateTool, removeTool, getTool }
})