Skip to content

About

How to make class (ES6 class) instances reactive via ref/reactive

Resources

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

It's an antipattern in case you want to inject reactive dependencies. Elaboration (reread this disclaimer after acquiantance with snippets): if you'd make a watcher of a reactive instance that changes the value of injected reactive property, recursion is going to happen.

VUE3-REACTIVE-ES6CLASS-EXAMPLE

Your questions:

  • How to mutate instance's properties via this. and track changes?
  • How to make reactive class (es6 class) instance in vue 3 basically?

To get your answer consider two snippets:

/src/classes/Counter.ts

In the first snippet we define Counter class that consists of:

  • count property
  • increment() method (mutating count via this.count++)
  • customized constructor() that makes possible mutating this directly from methods
// /src/classes/Counter.ts

import { reactive } from "vue";

export class Counter {
    count: number;

    constructor() {
        this.count = 0;
        const reactiveThis = reactive(this);
        Object.keys(this).forEach((key) => {
            // @ts-ignore // These two lines produce type errors, just ignore them
            if (typeof this[key] == "function") {
                // @ts-ignore
                reactiveThis[key] = this[key].bind(reactiveThis);
            }
        });
        return reactiveThis;
    }

    increment() {
        this.count++;
    }
}

/src/App.vue

<script setup lang="ts">
import { Counter } from "@/classes/Counter";
const instance = new Counter();
</script>

<template>
    <div> {{ instance.count }} </div>
    <button @click="instance.increment()"> increment </button>
    <button @click="instance.count = 69"> Mutate directly </button>
</template>

<style scoped></style>

About

How to make class (ES6 class) instances reactive via ref/reactive

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages