Skip to content

Instantly share code, notes, and snippets.

@Voltra
Created August 4, 2022 14:28
Show Gist options
  • Save Voltra/6032b0dce0635e13ec945fcabd2fad27 to your computer and use it in GitHub Desktop.
Save Voltra/6032b0dce0635e13ec945fcabd2fad27 to your computer and use it in GitHub Desktop.
(Vue 2) reactiveRefsHackMixin.js
/**
* Quite the hack-ish mixin, allows to have reactive computed properties that
* depend on data from `$refs` despite not being reactive itself
*/
export const reactiveRefsHackMixin = {
data() {
return {
/**
* Flag used to trigger computation of reactive data (do not edit manually)
* @private
* @type {boolean}
*/
refFlag_: true,
};
},
methods: {
/**
* Semi-magical method that allows "reactivity" even through refs
* Call this method manually when you need to trigger changes in refs-dependant values
* @protected
*/
toggleRefFlag_() {
this.refFlag_ = !this.refFlag_;
},
/**
* Get a value and make it reactive using the ref flag
* @template T
* @param {T} value
* @param {boolean} returnSelfOnEmpty - Whether to return {@link value} if it is empty and thus skip the ref flag check
* @returns {T}
* @protected
* @warning It abuses JS's `&&` and `||` to make it reusable with any type of input value
*/
withRefFlag_(value, returnSelfOnEmpty = true) {
if (returnSelfOnEmpty && !value) {
return value;
}
return (this.refFlag_ || true) && value;
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment