how can I use framework-independent JavaScript class instances with reactive state on vue-composition-api.
Given following class:
// CounterService / counter-service.ts
//
// this is a normal javascript class which is independent of vue
export const counterService = new (class CounterService {
private count: number = 0;
// should cause all components that use `getCount` to react.
addOne(): void {
this.count++;
}
// should be reactive
getCount(): number {
return this.count;
}
})()
Kind regards Rozbeh Chiryai Sharahi
most important hint: Use reactive or ref on all components involved (those that update and those that read).
// Component A / Counts.vue
<template>
<div>{{services.counterService.getCount()}}</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
setup() {
// You could also use ref, but i prefer to avoid the `.value`
const services = reactive({
counterService
})
return { services }
}
});
</script>
// Component B / IncrementCountButton.vue
<template>
<div @click="services.counterService.addOne()">Increment</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
setup() {
// You could also use ref, but i prefer to avoid the `.value`
const services = reactive({
counterService
})
return { services }
}
});
</script>
Kind regards Rozbeh Chiryai Sharahi