---
# System prepended metadata

title: 生命週期 (3-4)
tags: [3. Options API, Vue]

---

# 生命週期 (3-4)
###### tags: `Vue`、`3. Options API`
2022.3.3

## Vue 基本生命週期
![](https://i.imgur.com/gC1f3gn.png)
* ### 查看Vue 基本生命週期方法
```
 beforeCreate() {
    alert("beforeCreate!");
  },
  created() {
    alert("created!");
  },
  beforeMount() {
    alert("beforeMount");
  },
  mounted() {
    alert("mounted");
  },
  beforeUpdate() {
    alert("beforeUpdate");
  },
  updated() {
    alert("updated");
  },
  beforeUnmount() {
    alert("beforeUnmount");
  },
  unmounted() {
    alert("unmounted");
  },
```

## Router 生命週期
![](https://i.imgur.com/0RnZUYO.png)

* ### 查看Router 生命週期方法
router/index.js (beforeEnter)
```
  {
    path: '/',
    component: HomeView,
    beforeEnter: (to, from, next) => {
      alert('beforeEnter')
      next()
    }
```
View/HomeView (beforeRouteEnter)
```
 beforeRouteEnter() {
    alert("Home,beforeRouteEnter!");
  },
```



## beforeEach、afterEach 
![](https://i.imgur.com/PKPXIMq.png)
router/index.js (beforeEach、afterEach)
```
router.beforeEach((to, from, next) => {
  alert('beforeEach')
  next()
})

router.afterEach((to, from, next) => {
  alert('afterEach')
  next()
})

export default router
```

## 執行順序歸納
* 假設情境
![](https://i.imgur.com/xLiZsko.png)
* 載入頁面生命週期順序
1. App,Created!
2. App,beforeCreate!
3. App,beforeMount!
4. App,mounted!
5. router,beforeEach!
6. router,beforeEnter!
7. Home,beforeRouteEnter!
8. router,afterEach!
9. Home,beforeCreate!
10. Home,Created!
11. Home,beforeMount!
12. Home,mounted!





## 額外補充
### 1. v-if 與 v-show 生命週期差異
* v-if : 資料會循序漸進，銷毀(v-if = false)後就要從頭。
* v-show : 資料<HTML>語法會一直掛載，`v-show=false`資料不會銷毀。
    
### 2. 使用Keep Alive 維持生命週期

&emsp;&emsp;在keep alive中生命週期實體銷毀階段會變成，activated啟用、deactivate關閉啟用，此方法能讓資料不用再進入實體建立階段。    

```
<keep-alive>
    <div v-if="判斷式"> 資料 </div>
</keep-alive>    
```