feat: allow user tag creation

This commit is contained in:
Tim
2025-07-10 10:45:07 +08:00
parent 0df2acb65a
commit dd2485d7da
5 changed files with 94 additions and 8 deletions

View File

@@ -1,9 +1,15 @@
<template>
<Dropdown v-model="selected" :fetch-options="fetchTags" multiple placeholder="选择标签" />
<Dropdown
v-model="selected"
:fetch-options="fetchTags"
multiple
placeholder="选择标签"
remote
/>
</template>
<script>
import { computed } from 'vue'
import { computed, ref } from 'vue'
import { API_BASE_URL, toast } from '../main'
import Dropdown from './Dropdown.vue'
@@ -11,15 +17,37 @@ export default {
name: 'TagSelect',
components: { Dropdown },
props: {
modelValue: { type: Array, default: () => [] }
modelValue: { type: Array, default: () => [] },
creatable: { type: Boolean, default: false }
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const fetchTags = async () => {
const tags = ref([])
const loadTags = async () => {
if (tags.value.length) return
const res = await fetch(`${API_BASE_URL}/api/tags`)
if (!res.ok) return []
if (!res.ok) return
const data = await res.json()
return [{ id: 0, name: '无标签' }, ...data]
tags.value = [{ id: 0, name: '无标签' }, ...data]
}
const fetchTags = async (kw = '') => {
await loadTags()
let options = tags.value.filter(t =>
!kw || t.name.toLowerCase().includes(kw.toLowerCase())
)
if (
props.creatable &&
kw &&
!tags.value.some(t => t.name.toLowerCase() === kw.toLowerCase())
) {
options = [
...options,
{ id: `__create__:${kw}`, name: `创建"${kw}"` }
]
}
return options
}
const selected = computed({
@@ -34,6 +62,17 @@ export default {
toast.error('最多选择两个标签')
return
}
v = v.map(id => {
if (typeof id === 'string' && id.startsWith('__create__:')) {
const name = id.slice(11)
const newId = `__new__:${name}`
if (!tags.value.find(t => t.id === newId)) {
tags.value.push({ id: newId, name })
}
return newId
}
return id
})
}
emit('update:modelValue', v)
}