1

It's a demo in the article 11 Vue.js Lifecycle Hooks

I am confused why I can not get the DOM in mounted after 3 seconds, while can get the result as respected if console.log immediately.

<!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>
    }
})
Zia
  • 21
  • 3
  • 1
    see if `setTimeout(() => { console.log('mounted()',this.$el); },3000);` results in something less confusing - then search stackoverflow for a really good answer about how `this` works in javascript, and how it's different in *arrow* functions - or, if you can't bother searching ... https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Bravo Nov 09 '19 at 09:16

1 Answers1

0

You need to use the fat arrow syntax to ensure this is bound correctly:

setTimeout(() => {
  console.log('mounted()', this.$el);
}, 3000);

See What is the use of the JavaScript 'bind' method? for related info.

Decade Moon
  • 27,192
  • 7
  • 63
  • 85