为何Vue的mounted钩子中延迟3秒获取$el返回undefined?
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
thiscontext 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

