You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Vue的mounted钩子中延迟3秒获取$el返回undefined?

Why this.$el is Undefined in Your setTimeout Callback?

Hey there! I totally get why this is throwing you for a loop—let's break down exactly what's going on here and how to fix it.

The core issue here is the this context inside your setTimeout callback isn't pointing to your Vue instance. When you use a regular function as the setTimeout callback, this inside that function defaults to the global object (in browsers, that's window), not your Vue component. Since window doesn't have a $el property, you get undefined!

Let's confirm with your code snippet:

mounted:function(){
  setTimeout(function(){
    console.log('mounted()',this.$el); // `this` here = window, not your Vue instance
  },3000);
  console.log('mounted()',this.$el); // `this` here = Vue instance, so it works perfectly
}

Here are 3 straightforward fixes to solve this:

  • Use an arrow function (arrow functions inherit the this context from the surrounding code, which is your Vue instance here):

    mounted:function(){
      setTimeout(() => {
        console.log('mounted()',this.$el); // Now `this` points to your Vue component
      },3000);
    }
    
  • Save the Vue instance reference to a variable:

    mounted:function(){
      const vm = this; // Store the Vue instance in a variable
      setTimeout(function(){
        console.log('mounted()',vm.$el); // Use `vm` instead of `this` to access the instance
      },3000);
    }
    
  • Bind the Vue instance to the callback function:

    mounted:function(){
      setTimeout(function(){
        console.log('mounted()',this.$el);
      }.bind(this),3000); // Explicitly bind `this` to your Vue instance
    }
    

Pick whichever approach you prefer—all of them will make sure you can access $el correctly after the 3-second delay.

内容的提问来源于stack exchange,提问作者Zia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:29:05