Daily Challenge — Predict the Rendered Value

· 1 min read · 134 Words · -Views -Comments
<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.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover