vue3 reactive api in deep object can not re-render

1.2k views Asked by At

template:

<div>
      <label class="label">balance</label>
      <h3 class="title is-4">${{ lobby.balance }}</h3>
</div>

code:

setup() {
  const state = reactive({
     lobby: {},
  });

  state.lobby = new Lobby(); //settimeout change balance in constructor is not re-render

  setTimeout(() => {
    state.lobby.balance = 123; // re-render is work
  }, 1000);

  return {
    ...toRefs(state),
  };
}

Why isn't the balance change in the Lobby constructor reactive?

1

There are 1 answers

0
tony19 On BEST ANSWER

This would happen when Lobby()'s balance property is not declared as a ref:

class Lobby {
  balance = 0 // ❌ not a ref

  constructor() {
    setTimeout(() => {
      this.balance = 100 // ❌ not a ref, so no reactive
    }, 500)
  }
}

The solution would be to declare balance as a ref:

import { ref } from 'vue'

class Lobby {
  balance = ref(0) // 

  constructor() {
    setTimeout(() => {
      this.balance.value = 100 // 
    }, 500)
  }
}

demo