亲力亲为 vue 生命周期

网上关于vue生命周期的文章一抓一大把, 看了不少, 收获是有的, 但纸上得来终觉浅. 最终仍是决定本身上手,加深一下印象
测试版本
vue 2.5.2vue

程序设计以下函数

function log() {
    try {
      console.log('%c%s', 'color: blue', `===============data:foo ---> ${this.foo}=====================`)
    } catch (e) {
    }
    try {
      console.log('%c%s', 'color: blue', `===============props:bar ---> ${this.bar}=====================`)
    } catch (e) {
    }
    try {
      console.log('%c%s', 'color: blue', `===============computed:baz ---> ${this.baz}=====================`)
    } catch (e) {
    }
    try {
      console.log('%c%s', 'color: blue', `===============computed:bzz ---> ${this.bzz}=====================`)
    } catch (e) {
    }
  }
  export default {
    data() {
      return {
        foo: 'foo'
      }
    },
    props: {
      bar: {type: String, 'default': 'bar'}
    },
    computed: {
      baz() {
        return this.foo + this.bar
      },
      bzz() {
        return this.method()
      }
    },
    beforeCreate() {
      console.log('%c%s', 'color: red', '\n===============beforeCreate called===============')
      log.call(this)
    },
    created() {
      console.log('%c%s', 'color: red', '\n===============created called===============')
      log.call(this)
    },
    mounted() {
      console.log('%c%s', 'color: red', '\n===============mounted called===============')
      log.call(this)
    },
    methods: {
      method() {
        return 'method'
      }
    },
    beforeDestroy() {
      console.log('%c%s', 'color: red', '\n===============beforeDestroy called===============')
      log.call(this)
    },
    destroyed() {
      console.log('%c%s', 'color: red', '\n===============destroyed called===============')
      log.call(this)
    }
  }

程序运行结果以下:测试

加载时:

clipboard.png

卸载时:

clipboard.png

如下是个人总结(不对的地方欢迎拍砖):this

beforeCreate 钩子调用时:spa

获取data中的属性 获得undefined
获取props中的属性 报错
获取computed中的属性 获得undefined设计

其余钩子函数中均能正常的获取到全部的值code

值得注意的是 在created钩子执行后 computed 属性函数中能够访问到 data props methods 中的值
甚至在destroyed 函数中依然可以正常的访问到这些值.
欢迎挑错 ^_^blog

相关文章
相关标签/搜索