import axios from '../plugins/axios' import { defineStore } from 'pinia' export const useCategoriesStore = defineStore('categories', { state: () => ({ items: [], fetching: true, total: 0 }), getters: { // treeSelect: (state) => (id = null) => { // if (id) { // const foreach = (items) => { // return items.filter((item) => { // if (item.key != id) { // if (item.children) // item.children = foreach(item.children) // return true // } else return false // }) // } // return foreach(state.items) // } // return state.items // }, find: (state) => (id) => { if (id) { const foreach = (items) => { const item = items.find(({ key }) => key == id) if (item) return item for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.children) { const temp = foreach(item.children) if (temp) return temp } } } return foreach(state.items) } return ''; } }, actions: { async index() { this.fetching = true const {data} = await axios.get('/courseCategory') this.fetching = false return data if (status === 200) { const map = (items, parent = null) => { return items.map((item) => { const temp = { key: item._id, label: item.name, data: item } if (parent) temp.data.parentCategoryID = { [parent]: true } if (item.sub) { temp.children = map(item.sub, temp.key) delete temp.data.sub } return temp; }); } this.items = map(data) // this.items = data.items // this.total = data.total } }, async create(id) { const result = await axios.post('/courseCategory', { name: id.value }) return result; }, async store(form) { const result = await axios.post('/admin/categories', form) if (result.status === 201) this.items.unshift(result.data) return result; }, async update(id, form) { const result = await axios.put(`/admin/categories/${id}`, form) if (result.status === 200) { const index = this.items.findIndex(({ _id }) => _id == id) this.items[index] = result.data } return result; }, async remove(id) { const result = await axios.delete(`/courseCategory/${id}`) if (result.status === 200) { const index = this.items.findIndex(({ _id }) => _id == id) this.items.splice(index, 1) } return result; }, } })