vue3 reactive api in deep object cannot re-render

vue3 reactive api in deep object can not re-render

模板:

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

代码:

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),
  };
}

为什么 Lobby 构造函数中的 balance 更改不是反应式的?

Lobby()balance 属性 未声明为 ref 时会发生这种情况:

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

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

解决方案是将 balance 声明为 ref:

import { ref } from 'vue'

class Lobby {
  balance = ref(0) // 

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

demo