temporarily write into a Vue computed ref
vue-writable-computed-ref.ts edited
17 lines 504 B view raw
1import { computed, type Ref, shallowRef } from "vue"; 2 3export const writable = <T>(upstream: () => T) => { 4 // it's a bit weird, but this essentially guarantees that the ref gets reset 5 // immediately as expected. this also gets around the double-calling that 6 // using `watch` would cause. 7 const computable = computed(() => shallowRef(upstream())); 8 9 return computed<T>({ 10 get() { 11 return computable.value.value; 12 }, 13 set(next) { 14 computable.value.value = next; 15 }, 16 }); 17};