0

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.