Vue的生命周期
Vue示例被創(chuàng)建到銷毀的過程
Vue的鉤子函數(shù)詳解
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue的聲明周期和鉤子函數(shù)</title>
</head>
<body>
<div id="app">
<button @click="win">control</button>
{{msg}}
</div>
<script src="js/vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'hello'
},
// template: "<h1>{{msg}}-------ok</h1>",
methods: {
win() {
alert('ok');
}
},
// 生命周期(鉤子函數(shù) hook)函數(shù)就是vue實例在某一個時間點會自動執(zhí)行的函數(shù)
// 此時vue實例已經(jīng)進(jìn)行了基礎(chǔ)的初始化,但data數(shù)據(jù)還沒有綁定到vue的實例,此時,訪問不到data數(shù)據(jù)
beforeCreate() {
console.log('beforeCreate', this.msg);
},
// 此時,data數(shù)據(jù)已經(jīng)注入vue的實例,我們可以通過this訪問到data數(shù)據(jù)
created() {
console.log('created', this.msg);
},
// 此時,模板和數(shù)據(jù)已經(jīng)結(jié)合,編譯,但還沒有掛載到指定的掛載點上 (或者沒有掛載到指定的頁面元素上)
beforeMount() {
console.log('beforeMount', this.$el);
},
// 此時,編譯后的模板已經(jīng)掛載到掛載點上,我們會看到加載了數(shù)據(jù)的視圖的更新
mounted() {
console.log('mounted', this.$el);
},
// 當(dāng)有數(shù)據(jù)發(fā)生改變時,模板重新渲染之前,會觸發(fā)該事件。
beforeUpdate() {
console.log('beforeUpdate', this.$el.innerHTML);
},
// 當(dāng)模板重新渲染之后,觸發(fā)該事件
updated() {
console.log('updated', this.$el.innerHTML);
},
// 當(dāng)執(zhí)行vm.$destroy(),vue實例銷毀之前發(fā)生
beforeDestroy() {
console.log('beforeDestroy');
},
//vue實例銷毀之后發(fā)生,此時再改變數(shù)據(jù),不會觸發(fā)視圖更新(或者視圖重新渲染)
destroyed() {
console.log('destroyed');
}
});
//也可以通過vm.$mount注冊掛載點
// vm.$mount('#app');
</script>
</body>
</html>