Reputation: 21565
From the lifecycle diagram I am not able to determine when are data
evaluated.
See the example code below:
<template>
...
</template>
<script>
function generateUniqUserRef () {
return Math.random() + new Date().valueOf()
}
export default {
data() {
return {
user_ref: generateUniqUserRef()
}
}
}
</script>
Shall user_ref
get calculated only once OR should it re-evaluate again on re-render?
I'm just about to try it. I just would like to have a formal explanation possibly with a reference.
Upvotes: 2
Views: 206
Reputation: 31362
beforeCreate()
- called after the vue instance has been initialized by
new Vue({})
. Here the data is not observed i.e the vue instance
does not know what is initialized inside data option.
created()
-called after the vue instance is created. Here the vue insance know what reactive properties are inside data option and you can set up (change) any property inside data option
Shall user_ref get calculated only once OR should it re-evaluate again on re-render?
No it will get calculated only once. Re-render takes place when there is change in data and causes virtual dom to be re-rendered , so only the operations that are dependents on the dom take place again.
But it is better you calculate the user_ref
in the created()
as it will be called only once.
<script>
export default {
data() {
return {
user_ref: null
}
},
created(){
this.user_ref = Math.random() + new Date().valueOf();
}
}
</script>
You can run this code on you machine check the console logs
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
alert("hi i just ran"); // will only run once , not on every re-render
export default {
name: 'hello',
data () {
return {
msg: 'initial message'
};
},
beforeCreate(){
console.log('from before create', this.msg); // undefined
console.log('from before create', this.msg === 'initial message'); // false
},
created(){
console.log('from created', this.msg); // 'initial message'
console.log('from created', this.msg === 'initial message'); //true
},
mounted(){
// changes the msg
setTimeout(()=>{
this.msg = 'initial message changed';
}, 1000); // causes dom to re-render
},
beforeUpdate(){
console.log('from before update', this.msg) // 'initial message changed'
setTimeout(()=>{
this.msg = 'initial message changed again from before update';
}, 1000);
},
updated(){
console.log('from updated', this.msg)
}
}
</script>
<style scoped>
</style>
Source: options/lifecyclehooks
Upvotes: 1