生命週期鉤子函式
阿新 • • 發佈:2022-04-13
生命週期圖
1、官網原圖
2、我理解的圖
生命週期
鉤子函式 | 描述 |
---|---|
beforeCreate | 建立Vue例項之前呼叫 |
created | 建立Vue例項成功後呼叫(可以在此處傳送非同步請求後端資料) |
beforeMount | 渲染DOM之前呼叫 |
mounted | 渲染DOM之後呼叫 |
beforeUpdate | 重新渲染之前呼叫(資料更新等操作時,控制DOM重新渲染) |
updated | 重新渲染完成之後呼叫 |
beforeDestroy | 銷燬之前呼叫 |
destroyed | 銷燬之後呼叫 |
用的較多的
created:向後端發請求拿資料,傳送ajax請求
mounted:定時任務,延遲任務 js中
beforeDestroy:定時任務關閉,銷燬一些操作
定時器的開啟與關閉
this.t = setInterval(() => {
console.log('daada')
}, 3000)
clearInterval(this.t)
this.t = null
程式碼測試
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="app"> <button @click="handleC">點我顯示元件</button><child v-if="is_show"></child> <hr> </div> </body> <script> // 1 定義個元件---》生命週期 Vue.component('child', { template: ` <div> <h1>{{name}}</h1> <button @click="handleC">點我彈窗</button> </div>`, data() { return { name: "lqz", t:'', } }, methods: { handleC() { this.name = "彭于晏" alert(this.name) } }, // 生命週期鉤子函式8個 beforeCreate() { console.log('當前狀態:beforeCreate') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, created() { // 向後端載入資料 console.log('當前狀態:created') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, beforeMount() { console.log('當前狀態:beforeMount') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, mounted() { console.log('當前狀態:mounted') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀 態:', this.name) //用的最多,向後端載入資料,建立定時器等 // setTimeout:延遲執行 // setInterval:定時執行,每三秒鐘列印一下daada this.t = setInterval(() => { console.log('daada') }, 3000) }, beforeUpdate() { console.log('當前狀態:beforeUpdate') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, updated() { console.log('當前狀態:updated') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, beforeDestroy() { console.log('當前狀態:beforeDestroy') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) }, destroyed() { console.log('當前狀態:destroyed') console.log('當前el狀態:', this.$el) console.log('當前data狀態:', this.$data) console.log('當前name狀態:', this.name) //元件銷燬,清理定時器 clearInterval(this.t) this.t = null // console.log('destoryed') }, }) var vm = new Vue({ el: '#app', data: { is_show: false }, methods: { handleC() { this.is_show = !this.is_show } }, }) </script> </html>