Integrating JavaScript Classes with Vue's Reactive System

Hi Vue community!

I’m trying to improve our app’s architecture by using JavaScript Classes to manage business logic. But I’m hitting a snag with Vue’s reactivity.

Our old setup was messy. Business logic was all over the place. We cleaned it up using Vue stores, which helped a lot.

Now I want to use Classes to group related logic. The idea is when one thing changes in a Class instance, it updates other stuff automatically.

The problem? Vue doesn’t seem to notice these internal Class changes. The UI isn’t updating like it should.

Has anyone cracked this puzzle before? Any tips or examples on making Classes play nice with Vue’s reactivity? Or should I be looking at a totally different approach?

Thanks for any help!

I’ve actually been working on a similar problem recently. One approach that’s been working well for me is using Vue 3’s ref() function to create reactive references for class properties. Here’s a quick example:

import { ref, reactive } from 'vue'

class BusinessLogic {
  constructor() {
    this.data = ref({})
    this.status = ref('idle')
  }

  updateData(newData) {
    this.data.value = { ...this.data.value, ...newData }
    this.status.value = 'updated'
  }
}

const logic = reactive(new BusinessLogic())

This way, you can use your class methods to update the reactive properties, and Vue will pick up on the changes. You might need to adjust your component code to use .value when accessing these properties, but it’s a small price to pay for keeping your business logic nicely encapsulated.

Another tip: if you’re using TypeScript, you can create interfaces for your class properties to maintain type safety. It’s been a game-changer for our codebase organization.

I’ve faced similar challenges integrating classes with Vue’s reactivity system. One effective approach I’ve found is using Vue’s reactive() function from the Composition API. It allows you to create reactive objects from your class instances.

Here’s a basic example:

import { reactive } from 'vue'

class MyClass {
  // Your class implementation
}

const reactiveInstance = reactive(new MyClass())

This ensures that changes to the class instance trigger updates in your components. Remember to use the reactive instance in your template bindings and computations.

Another option is to use getters and setters in your class, then wrap the instance with reactive(). This gives you more control over which properties trigger updates.

These methods have helped me maintain clean architecture while leveraging Vue’s reactivity. Hope this helps with your refactoring efforts!

hey ClimbingLion, been there! vue’s reactivity can be tricky with classes. have u tried using Vue.observable() to wrap ur class instances? it makes em reactive. or u could use computed props in ur components to watch for changes. both ways worked for me. good luck!