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.
- How to mutate instance's properties via
this.and track changes? - How to make reactive class (es6 class) instance in vue 3 basically?
In the first snippet we define Counter class that consists of:
countpropertyincrement()method (mutatingcountviathis.count++)- customized
constructor()that makes possible mutatingthisdirectly 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++;
}
}<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>