Daily Challenge — Predict the Rendered Value

Daily Challenge — Predict the Rendered Value

10月 31, 2020 · 1 分钟阅读时长 · 134 字 · -阅读 -评论
<template>
  <div>{{ a.b }}</div>
</template>
<script>
export default {
  data() {
    return {
      a: {}
    };
  },
  created() {
    this.a.b = 1;
  },
  mounted() {
    this.a.b = 2;
  }
};
</script>

Analysis

  • During instance initialization, Vue converts properties into getters/setters, so the property must exist on data to become reactive. Because a.b isn’t declared up front, it’s non-reactive and the view won’t update when it changes.
  • Lifecycle-wise, created runs before mounted, so the displayed value is 1.
  • The question probes two concepts: Vue’s reactivity system and the timing difference between created and mounted.

Try it yourself in this sandbox: code link

Summary

Even though this example is in Vue, similar pitfalls show up in React and Angular with their own twists. For instance, React tracks state by reference; without setState, the view won’t re-render.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源