【问题标题】:vue3 reactive api in deep object can not re-render深层对象中的vue3反应api无法重新渲染
【发布时间】:2021-01-19 22:40:46
【问题描述】:

模板:

<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 更改没有反应?

【问题讨论】:

    标签: typescript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 2020-07-04
      • 1970-01-01
      • 2021-12-22
      • 2022-01-25
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 2021-03-21
      相关资源
      最近更新 更多