Last active
August 27, 2020 23:16
-
-
Save johnsoncodehk/1ecf6907644bd06c0650a0a24ee868e3 to your computer and use it in GitHub Desktop.
Vue 3 "cheap" computed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { computed, ref } from "vue"; | |
import { ComputedGetter, pauseTracking, resetTracking } from "@vue/reactivity"; | |
// if no version, not work for objects/arrays... | |
export function cheapComputed<T, K = T>(getValue: ComputedGetter<T>, getVersion?: ComputedGetter<K>) { | |
const value = computed(getValue); | |
const version = getVersion ? computed(getVersion) : value; | |
const lastValue = ref<T>(); | |
const lastVersion = ref<K>(); | |
const changed = computed(() => version.value !== lastVersion.value); | |
return { | |
get value() { | |
update(); | |
return lastValue.value as T; | |
}, | |
get version() { | |
update(); | |
return lastVersion.value as K; | |
}, | |
} | |
function update() { | |
if (changed.value) { | |
pauseTracking(); | |
lastVersion.value = version.value as K; | |
lastValue.value = value.value; | |
resetTracking(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment