Subscribe on changes!

Reactivity not support `class`

avatar
Jun 8th 2022

Vue version

latest

Link to minimal reproduction

minimal reproduction link

Steps to reproduce

  1. declare a class
  2. declare a ref or reactive
  3. declare a field with ref in constructor function and declare class property setField, e.g. setField(value) { this.field.value = value; }
  4. ref.value = new this class
  5. call ref.value.setField('xxx')
  6. throw error: Cannot create property 'value' on string

relation issue with pinia https://github.com/vuejs/pinia/issues/1346

What is expected?

normal assignment value

What is actually happening?

throw error: Cannot create property 'value' on string

System Info

No response

Any additional comments?

No response

avatar
Jun 8th 2022

This is expected behavior.

  • Objects wrapped by reactive() automatically unwraps properties that are refs.
  • When a class instance is wrapped by reactive(), this inside its methods will be the reactive proxy.

The general rule of thumb: if you want to make something reactive, do not mix usage of its raw version and its reactive proxy. Instead, only use the reactive version.

In your case:

class Foo {
  constructor() {
    this.field = ''
  }

  setField(value) {
    this.field = value;
  }
}

const foo = reactive(new Foo())