网上关于vue生命周期的文章一抓一大把, 看了很多, 收获是有的, 但纸上得来终觉浅. 最终还是决定自己上手,加深一下印象
测试版本
vue 2.5.2
程序设计如下
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)}}
程序运行结果如下:
加载时:
卸载时:
以下是我的总结(不对的地方欢迎拍砖):
beforeCreate 钩子调用时:
获取data中的属性 得到undefined
获取props中的属性 报错
获取computed中的属性 得到undefined
其他钩子函数中均能正常的获取到所有的值
值得注意的是 在created钩子执行后 computed 属性函数中可以访问到 data props methods 中的值
甚至在destroyed 函数中依然能够正常的访问到这些值.
欢迎挑错 ^_^