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
datato become reactive. Becausea.bisn’t declared up front, it’s non-reactive and the view won’t update when it changes. - Lifecycle-wise,
createdruns beforemounted, so the displayed value is 1. - The question probes two concepts: Vue’s reactivity system and the timing difference between
createdandmounted.
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.

