少侠请重新来过 - Vue学习笔记(二) - Vue生命周期
生活随笔
收集整理的這篇文章主要介紹了
少侠请重新来过 - Vue学习笔记(二) - Vue生命周期
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Vue 生命周期和鉤子
每一個(gè)vue實(shí)例創(chuàng)建時(shí),會(huì)經(jīng)歷一段初始化的過程,同時(shí)會(huì)調(diào)用其生命周期鉤子,實(shí)例的鉤子this指向它的Vue實(shí)例,不需要在鉤子用箭頭函數(shù)。
<template><div><p>{{msg}}</p></div> </template><script> export default {data(){return{msg:'vue'}},beforeCreate() {//組件剛剛被創(chuàng)建,組件屬性計(jì)算之前時(shí)調(diào)用console.log('-- beforeCreate --'); // 輸出 -- beforeCreate --console.log(`this.msg = ${this.msg}`); // 輸出 undefinedconsole.log(`this.$el = `); // 輸出 this.$el =console.log(this.$el) // 輸出 undefined},created() {//組件剛剛創(chuàng)建完成,屬性已經(jīng)綁定,但是還未生成dom節(jié)點(diǎn),所以$el不存在,msg已經(jīng)被綁定this.log('created')// 輸出 -- created --// 輸出 this.msg = vue// 輸出 this.$el =// 輸出 undefined},beforeMount() {//模板-編譯-掛載之前,Compile,此時(shí)-> this.log('beforeMount')// 輸出 -- beforeMount --// 輸出 this.msg = vue// 輸出 this.$el =// 輸出 undefined},mounted() {//模板掛載之后,此時(shí)$el已經(jīng)有dom節(jié)點(diǎn)值this.log('mounted')// 輸出 -- mounted --// 輸出 this.msg = vue// 輸出 this.$el =// 輸出 dom節(jié)點(diǎn)this.msg = 'hello'// 組件更新之前會(huì)調(diào)用beforeUpdate// 輸出 -- beforeUpdate --// 輸出 this.msg = vue// 輸出 this.$el =// 輸出 dom節(jié)點(diǎn)// -->// 組件更新之前會(huì)調(diào)用updated// 輸出 -- updated --// 輸出 this.msg = hello// 輸出 this.$el =// 輸出 dom節(jié)點(diǎn)},beforeUpdate() {this.log('beforeUpdate')},updated() {this.log('updated')},beforeDestory() {//組件銷毀前調(diào)用this.log('beforeDestory')},destoryed() {//組件銷毀后調(diào)用this.log('destoryed')},activated() {// 組件使用keep-alive,被激活時(shí)調(diào)用this.log('activated');// 輸出 -- activated --// 輸出 this.msg = hello// 輸出 this.$el =// 輸出 dom節(jié)點(diǎn)},deactivated() {//組件使用keep-alive,組件被移除時(shí)候調(diào)用this.log('deactivated');// 輸出 -- deactivated --// 輸出 this.msg = hello// 輸出 this.$el =// 輸出 dom節(jié)點(diǎn)},methods:{log(str){console.log(`-- ${str} --`)console.log(`this.msg = ${this.msg}`);console.log(`this.$el = `);console.log(this.$el)}} } </script> 復(fù)制代碼生命周期使用
- created 實(shí)例創(chuàng)建完成后調(diào)用,在此階段完成了對(duì)數(shù)據(jù)的觀測,但是尚未掛載,可以在此函數(shù)中初始化一些數(shù)據(jù)
- mounted el掛載到實(shí)例上后調(diào)用,經(jīng)常第一個(gè)業(yè)務(wù)邏輯的出發(fā)點(diǎn)
- beforeDestroy 在實(shí)例銷毀時(shí)候調(diào)用,可以在這事件中主動(dòng)解綁一些監(jiān)聽事件
轉(zhuǎn)載于:https://juejin.im/post/5bc034fbe51d450e4d302810
總結(jié)
以上是生活随笔為你收集整理的少侠请重新来过 - Vue学习笔记(二) - Vue生命周期的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis集群部署
- 下一篇: HTML5调用手机前置摄像头或后置摄像头