Vue生命周期

示例代码:

<template>
  <div>
    <text class="title" v-for="(value, i) in list" :key="i" >{{value}}</text>
  </div>
</template>

<style scoped>
  .title {font-size: 48px;}
</style>

<script>
  var initMessage
  module.exports = {
    data: function () {
      return {
        list: ['Lifecycle List']
      }
    },
    init: function () {
      initMessage = 'component init: nothing more happen even the data initialization'
      console.log('init:', this.list)
    },
    created: function () {
      this.list.push(initMessage)
      this.list.push('component created: data observed')
      console.log('created:', this.list)
    },
    mounted: function () {
      this.list.push('component mounted: virtual dom generated')
      console.log('mounted:', this.list)
    }
  }
</script>

控制台打印结果:

[Log] created: – ["Lifecycle List", undefined, "component created: data observed"]

[Log] mounted: - ["Lifecycle List", undefined, "component created: data observed", "component mounted: virtual dom generated"]

日志中,init 方法中的内容并没有打印出来,而且 this.list.push(initMessage) 的结果为 undefined,整个 init 方法好像并没有执行;
这是因为 init 内一般用于初始化一些内部变量,绑定一些自定义事件,这时还没有数据绑定,没有创建vdom,所以不能通过this获取到data和methods,也不能获取vdom的节点

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容