【问题标题】:Why get undefined after the render of the DOM in the following case?为什么在以下情况下渲染 DOM 后会出现 undefined?
【发布时间】:2019-11-09 08:43:06
【问题描述】:

11 Vue.js Lifecycle Hooks文章中的demo

我很困惑为什么我不能在 3 秒后获得 mounted 中的 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>
    }
})

【问题讨论】:

  • 看看 setTimeout(() =&gt; { console.log('mounted()',this.$el); },3000); 是否会产生一些不那么令人困惑的结果 - 然后搜索 stackoverflow 以获得关于 this 如何在 javascript 中工作以及它在 arrow 函数中的不同之处的非常好的答案- 或者,如果你懒得搜索……stackoverflow.com/questions/3127429/…

标签: javascript vue.js dom settimeout lifecycle-hook


【解决方案1】:

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

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

相关信息请参见What is the use of the JavaScript 'bind' method?

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-04-16
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多