Skip to content

Instantly share code, notes, and snippets.

@johnsoncodehk
Last active August 27, 2020 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnsoncodehk/1ecf6907644bd06c0650a0a24ee868e3 to your computer and use it in GitHub Desktop.
Save johnsoncodehk/1ecf6907644bd06c0650a0a24ee868e3 to your computer and use it in GitHub Desktop.
Vue 3 "cheap" computed
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