React Native开发React Native开发经验集

生命周期

2018-08-08  本文已影响4人  Valley4Z

示例代码:

<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的节点

上一篇下一篇

猜你喜欢

热点阅读