網上關於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) } }
程序運行結果以下:測試
加載時:
卸載時:
如下是個人總結(不對的地方歡迎拍磚):this
beforeCreate 鉤子調用時:spa
獲取data中的屬性 獲得undefined
獲取props中的屬性 報錯
獲取computed中的屬性 獲得undefined設計
其餘鉤子函數中均能正常的獲取到全部的值code
值得注意的是 在created鉤子執行後 computed 屬性函數中能夠訪問到 data props methods 中的值
甚至在destroyed 函數中依然可以正常的訪問到這些值.
歡迎挑錯 ^_^blog