-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-form.js
68 lines (60 loc) · 1.7 KB
/
use-form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export const useForm = (serviceName) => {
const { api } = useFeathers()
const service = api.service(serviceName)
const get = (id, defValues) => {
const $id = isRef(id) ? id : ref(id)
const isNew = ref($id.value === 'new')
const error = ref(null)
const isPending = ref(false)
const newData = ref(null)
const hasLoaded = computed(() => !!data.value && !!clone.value)
const data = computed(() =>
newData.value
? newData.value
: service.store.getFromStore($id.value)
)
const clone = computed(() => {
const item = service.store.getFromStore($id.value)
return item.value ? item.value.clone() : {}
})
if (isNew.value) {
newData.value = service.new(defValues || {})
isPending.value = false
} else {
const _get = async () => {
try {
const response = await service.get($id.value)
console.log(response)
} catch (err) {
error.value = err
} finally {
isPending.value = false
}
}
watch($id, async () => await _get(), { immediate: true })
}
const save = async () => {
isPending.value = true
try {
return await clone.value.save()
} catch (err) {
error.value = err
} finally {
isPending.value = false
}
}
return reactive({
isNew: computed(() => isNew.value),
isEdit: computed(() => !isNew.value),
data,
clone,
isPending: computed(() => isPending.value),
hasLoaded: computed(() => hasLoaded.value),
error: computed(() => error.value)
})
}
return {
service,
get
}
}