vue 生命周期函數了解
在 vue 中, 生命周期函數可了解為 "在某個時刻, 會自動執行的函數". 先直覺感受一下圖示.
一共就八個:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue 生命周期函數</title>
<script src="./js/[email protected]"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 生命周期函數: 在某一個時刻會自動執行的函數
const app = Vue.createApp({
data() {
return {
message: 'hello world'
}
},
methods: {
handleItemClick() {
alert('click');
}
},
// 1. 在執行個體生成之前
beforeCreate() {
console.log('beforCreate');
},
// 2. 在執行個體生成之後
created() {
console.log('created');
},
// 3. 在元件内容被渲染到頁面之前
beforeMount() {
console.log(document.getElementById('root').innerHTML, 'beforMount');
},
// 4. 在元件内容被渲染到頁面之後
mounted() {
console.log(document.getElementById('root').innerHTML, 'mounted');;
},
// 5. 當 data 中的資料發生變化時, 會立即自動執行
beforeUpdate() {
console.log(document.getElementById('root').innerHTML, 'beforeUpdate');;
},
// 6. 當 data 中的資料發生變化, 頁面重新渲染後後執行
updated() {
console.log(document.getElementById('root').innerHTML, 'updated');
},
// 7. 當 Vue 應用失效時, 自動執行的函數
beforeUnmount() {
console.log('beforUnmount');
},
// 8. 當 Vue 應用失效時, 且dom完全銷毀的時候
unmounted() {
console.log('unmounted');
},
template: `<div v-on:click=handleItemClick>{{message}}</div>`
})
const vm = app.mount('#root');
</script>
</html>
再來重複一遍吧, 這個也是重在了解和能基本使用即可, 沒有什麼技巧的.
- beforCreate ( ) : 在執行個體生成前執行
- created ( ) : 在執行個體生成後執行
- beforeMount ( ) : 在元件内容被渲染到頁面之前執行
- mounted ( ) : 在元件内容被渲染到頁面之後執行
- beforUpdate ( ): 當 data 中的資料發生變化時, 會立即自動執行
- updated ( ) : 當 data 中的資料發生變化後, 頁面重新渲染後執行
- beforUnmount ( ) : 當 vue 應用失效時, 會自動執行
- unmounted ( ) : 當 vue 應用失效後, 且 dom 元素完全被銷毀之後執行