export default { setup() { const { ref, computed } = Vue; const columns = ["title", "overview", "categories", "date"]; const loaded = ref(false); const currentPage = ref(""); const pads = ref([]); const currentSort = ref("date"); const currentSortDir = ref("desc"); const categories = ref([]); const selected = ref(new Set()); const toggle = function (tag) { selected.value.has(tag) ? selected.value.delete(tag) : selected.value.add(tag); }; fetch("api") .then((res) => res.json()) .then((data) => { pads.value = data.pads; pads.value.map( (pad) => (pad.categories = pad.categories .split(",") .map((category) => category.trim())) ); categories.value = Array.from( new Set([...pads.value.map((pad) => pad.categories)].flat()) ).sort(); currentPage.value = data.page; loaded.value = true; }); const sortedPads = computed(() => { return filteredPads.value.sort((a, b) => { let modifier = 1; if (currentSortDir.value === "desc") modifier = -1; if (currentSort.value === "date") { a[currentSort.value] = new Date(a[currentSort.value]); b[currentSort.value] = new Date(b[currentSort.value]); } if (a[currentSort.value] < b[currentSort.value]) return -1 * modifier; if (a[currentSort.value] > b[currentSort.value]) return 1 * modifier; return 0; }); }); const sort = function (s) { if (s == currentSort.value) { currentSortDir.value = currentSortDir.value === "asc" ? "desc" : "asc"; } currentSort.value = s; }; const filteredPads = computed(() => { if (selected.value.size == 0) return pads.value; else return pads.value.filter((pad) => { return pad.categories.some((category) => selected.value.has(category)); }); }); const formatDate = function (date) { return `${String(date.getDate()).padStart(2, "0")}-${String( date.getMonth() + 1 ).padStart(2, "0")}-${date.getFullYear()}`; }; return { pads, columns, currentPage, loaded, filteredPads, categories, selected, sortedPads, currentSort, currentSortDir, toggle, sort, formatDate, }; }, template: `
Fetching pads from {{currentPage}}
{{column }} {{ currentSortDir == 'asc' ? '▼' : '▲'}} | |||
---|---|---|---|
{{pad.title}} |
{{pad.overview}} |
{{category}} | {{formatDate(pad.date)}} |