cineclub-site/front/composables/modelWrapper.ts

29 lines
794 B
TypeScript
Raw Normal View History

2022-04-09 02:49:16 +02:00
import { computed, getCurrentInstance } from "vue"
export function useModel<Type>(
propName = "modelValue",
options: { type?: "object" | "array" } = {}
) {
2023-01-29 00:07:25 +01:00
const vm = getCurrentInstance()?.proxy
if (!vm) throw "useModel is called without an instance"
2022-04-09 02:49:16 +02:00
2023-01-29 00:07:25 +01:00
let valueToSet: (arg0: Type) => Type
// @ts-expect-error strange typing
if (options.type === "object") valueToSet = (value: object) => ({ ...value })
else if (options.type === "array")
// @ts-expect-error strange typing
2022-07-13 00:39:33 +02:00
valueToSet = (value: unknown[]) => [...value]
2023-01-29 00:07:25 +01:00
else valueToSet = (value: Type) => value
2022-04-09 02:49:16 +02:00
return computed<Type>({
get() {
2023-01-29 00:07:25 +01:00
// @ts-expect-error strange typing
2022-04-09 02:49:16 +02:00
return vm.$props[propName]
},
set(value) {
vm.$emit(`update:${propName}`, valueToSet(value))
},
})
}