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

 点提土八撇又254 发布于 2022-11-09 05:01

首先,我们来看一下 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.

  • 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 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.

  • 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 的结果明明显示已经绑定了该属性。

这是为啥呢?谢谢。

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

    2022-11-12 01:46 回答
  • 这是控制台的原因,看我这个截图你能不能明白:

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

    2022-11-12 01:46 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有