1

这是文章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>
    }
})
4

1 回答 1

0

您需要使用粗箭头语法来确保this正确绑定:

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

请参阅JavaScript 'bind' 方法的用途是什么?获取相关信息。

于 2019-11-09T11:05:56.313 回答