首先,我们来看一下 Vue 2 的官方文档中关于生命周期中 created
beforeMount
和 mounted
的描述:
created
Type:
Function
Details:
Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the
$el
property will not be available yet.
See also: Lifecycle Diagram
beforeMount
Type:
Function
Details:
Called right before the mounting begins: the
render
function is about to be called for the first time.This hook is not called during server-side rendering.
See also: Lifecycle Diagram
mounted
Type:
Function
Details:
Called after the instance has just been mounted where
el
is replaced by the newly createdvm.$el
. If the root instance is mounted to an in-document element,vm.$el
will also be in-document whenmounted
is called.This hook is not called during server-side rendering.
See also: Lifecycle Diagram
如上诉述, $el
属性在这个 created
的阶段还是不可用的,直到 mounted
之后,我们才能获取到 $el 属性。
我使用如下代码进行了测试:
created: function () {
console.log('----------in created----------')
console.log(this.$el)
},
beforeMount:function(){
console.log('-----in before mount----------')
console.log(this.$el)
},
mounted:function(){
console.log('-----in mounted----------')
console.log(this.$el)
},
输出结果为:
这是一个符合预期的结果。
之后处于好奇,我在 created
中 log 了一下 this
, 输出结果如下:
我发现在这时候的 Vue 实例中 $el
明明已经存在了啊。
之后我去翻了下 Vue 2 的源码,查找到的代码段如下:
//....
initMixin(Vue) // Vue 实例在这里调用了 created 钩子绑定的函数,此时 Vue 的实例还没有设置 $el 属性。
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue) // Vue 实例在这里第一次为实例设置了 $el 属性,在之后调用 mounted 钩子所绑定的函数。
renderMixin(Vue)
//...
所以很奇怪为什么在 created
的阶段中输出的 this
上就已经绑定了 $el
属性呢?
而且除了 $el
之外,其他的一些实例属性也有类似的问题,在 created
阶段明明还没有被创建,而且也无法访问到,但在输出 this
的结果明明显示已经绑定了该属性。
这是为啥呢?谢谢。
这是控制台的原因,看我这个截图你能不能明白:

虽然我在后面的函数中才给
obj
设属性,但是之前console的obj展开后也能看到后面设置的属性