I'm trying to create a Vue components instance programmatically and I got some problems.
<!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
<meta charset="utf-8">
</head>
<body>
<script>
var vm = new Vue({
data:{
mes:'hello vue'
},
template:'<div>{{mes}}</div>',
mounted(){
console.log(this.$el.getBoundingClientRect().height) // get 0
this.$nextTick(()=>{
console.log(this.$el.getBoundingClientRect().height) //get height
})
}
}).$mount()
document.body.appendChild(vm.$el)
<script>
</body>
</html>
My question :
- According to docs about the Vue lifecycle, the mounted hooks function should be called after " Create
vm.$el
and replace 'el' with it ". So I just thought the mounted hooks function should be called after document.body appendvm.$el
. While the fact is that it is called right aftervm.$mount()
- Why
this.$el.getBoundingClientRect().height
get 0 if it is not putted in vm.$nextTick function ? - As far as I know,
$nextTick
function created a microtask, while the browser UI render should be a macro task. So I don't know why we get the correct height if it is in $nextTick function.
The DOM height should be calculated after it is putted in the page ( I meandocument.body.appendChild(vm.$el)
)?
I thought microtask get handled before macro task, so even in$nextTick
function we shouldn't get the right height. But it did. I wonder why.