关于 Vue 2 在 Lifecycle 中 实例属性的绑定问题,以 $el 为例。

首先,我们来看一下 Vue 2 的官方文档中关于生命周期中 created beforeMountmounted 的描述:

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.

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.

mounted

  • Type: Function

  • Details:

Called after the instance has just been mounted where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

This hook is not called during server-side rendering.

如上诉述, $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 的结果明明显示已经绑定了该属性。

这是为啥呢?谢谢。

阅读 7.2k
2 个回答

这是控制台的原因,看我这个截图你能不能明白:
图片描述

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

控制台异步。。。。实际测试需要以最精准的实时打印为准

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题