Vue 組件生命周期鈎子
# 1)一個組件從創建到銷毀的整個過程,就稱之為組件的生命周期 # 2)在組件創建到銷毀的過程中,會出現眾多關鍵的時間節點,
如: 組件要創建了、組件創建完畢了、組件數據渲染完畢了、組件要被銷毀了、組件銷毀完畢了 等等時間節點,
每一個時間節點,vue都為其提供了一個回調函數(在該組件到達該時間節點時,就會觸發對應的回調函數,在函數中就可以完成該節點需要完成的業務邏輯) # 3)生命周期鈎子函數就是 vue實例的成員
beforeCreate
組件創建了,但數據和方法還未提供時
# 該鈎子需要掌握,一般該組件請求后台的數據,都是在該鈎子中完成 # 1)請求來的數據可以給頁面變量進行賦值 # 2)該節點還只停留在虛擬DOM范疇,如果數據還需要做二次修改再渲染到頁面,可以在beforeMount、mounted鈎子中添加邏輯處理
export default { .... beforeCreate(){ console.log('組件創建了,但數據和方法海未提供'); console.log(this.title); # undefined console.log(this.alterTitle); # undefined }, }
created
組件創建了,數據和方法已提供,頁面還未渲染
export default { .... created(){ console.log('組件創建了,數據和方方法已提供'); console.log(this.title); # 有值 console.log(this.alterTitle); # 有值 }, }
destroyed
數據銷毀完畢后
export default { .... destroyed() { console.log('組件銷毀完畢') } }
""" 1) router-link會被解析為a標簽,用to完成指定路徑跳轉,但是不能添加系統事件(因為是組件標簽) 2) 在js方法中可以用 this.$router.push('路徑') 完成邏輯跳轉 3) 在js方法中可以用 this.$route.path 拿到當前請求的頁面路由 """
<template> <div class="nav"> <!--采用vue-router完成頁面跳轉,不能采用a標簽(會發生頁面刷新,本質就是重新加載了一次項目界面)--> <ul> <li @click="changePage('/')" :class="{active: currentPage === '/'}"> <!--<a href="/">主頁</a>--> <!--<router-link to="/">主頁</router-link>--> 主頁 </li> <li @click="changePage('/red')" :class="{active: currentPage === '/red'}"> <!--<router-link to="/red">紅頁</router-link>--> 紅頁 </li> <li @click="changePage('/blue')" :class="{active: currentPage === '/blue'}"> <!--<router-link to="/blue">藍頁</router-link>--> 藍頁 </li> <li @click="changePage('/tan')" :class="{active: currentPage === '/tan'}"> <!--<router-link to="/tan">土頁</router-link>--> 土頁 </li> </ul> </div> </template> <script> export default { name: "Nav", data() { return { // 沒渲染一個頁面,都會出現加載Nav組件,currentPage就會被重置, // 1)在點擊跳轉事件中,將跳轉的頁面用 數據庫 保存,在鈎子函數中對currentPage進行數據更新 // currentPage: localStorage.currentPage ? localStorage.currentPage: '' // 2)直接在created鈎子函數中,獲取當前的url路徑,根據路徑更新currentPage currentPage: '' } }, methods: { changePage(page) { // console.log(page); // 當Nav出現渲染,該語句就無意義,因為在data中將currentPage重置為空 // this.currentPage = page; // 有bug,用戶不通過點擊,直接修改請求路徑完成頁面跳轉,數據庫就不會更新數據 // localStorage.currentPage = page; // 任何一個標簽的事件中,都可以通過router完成邏輯條件 // console.log(this.$route); // 管理路由數據 // console.log(this.$router); // 管理路由跳轉 this.$router.push(page); // 路由的邏輯跳轉 } }, // 當前組件加載成功,要根據當前實際所在的路徑,判斷單選激活標簽 created() { // console.log(this.$route.path); this.currentPage = this.$route.path; } } </script> <style scoped> .nav { width: 100%; height: 60px; background-color: orange; } .nav li { float: left; font: normal 20px/60px '微軟雅黑'; padding: 0 30px; } .nav li:hover { cursor: pointer; background-color: aquamarine; } .nav li.active { cursor: pointer; background-color: aquamarine; } </style>