这是文章11 Vue.js Lifecycle Hooks中的一个演示
我很困惑为什么我不能mounted
在 3 秒后得到 DOM,而如果console.log
立即得到尊重的结果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="lifecycle">
<h1>{{ title }}</h1>
<button @click="title='New Title'">Update Title</button>
</div>
<script src='practice.js'></script>
</body>
</html>
new Vue({
el:'#lifecycle',
data:{
title:'hello Vue'
},
beforeCreate:function(){
console.log("beforeCreate()",this.title);
},
created:function(){
console.log('created()',this.title);
},
beforeMount:function(){
console.log('beforeMount()',this.$el);
},
// confusion
mounted:function(){
setTimeout(function(){
console.log('mounted()',this.$el); // result: undefined
},3000);
// console.log('mounted()',this.$el);
// result : <div id="lifecycle">...</div>
}
})