Daily Challenge — Predict the Rendered Value

A Vue question on reactivity and lifecycle: what value renders on the page, and why.

Oct 31, 2020 · 1 min read · 134 Words · -Views -Comments · Programming
JavaScript Vue 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

<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