Vue
组件实例在创建时要经历一些列的初始化步骤,在此过程中vue
会在合适的时机,调用特定函数,从而让开发中有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子生命周期整体分为四个阶段:分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后
Vue2
的生命周期创建阶段:
beforeCreate
、created
挂载阶段:beforeMount
、mounted
更新阶段:beforeUpdate
、updated
销毁阶段:beforeDestroy
、destroyed
Vue3
的生命周期创建阶段:
setup
挂载阶段:onBeforeMount
、onMounted
更新阶段:onBeforeUpdate
、onUpdated
卸载阶段:onBeforeUnmount
、onMounted
onMounted
(挂载完毕)、onUpdated
(更新完毕)、onBeforeUnmount
(卸载之前)<template>
<div>
<h2>当前值为{{ num }}</h2>
<button @click="changeSum">点击加1</button>
</div>
</template>
<script setup lang="ts">
import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue'
let num = ref(0)
function changeSum() {
num.value += 1
}
console.log('创建')
onBeforeMount(() => {
console.log('挂载之前')
})
onMounted(() => {
console.log('挂载完毕')
})
onBeforeUpdate(() => {
console.log('更新之前')
})
onUpdated(() => {
console.log('更新完毕')
})
onBeforeUnmount(() => {
console.log('卸载之前')
})
onUnmounted(() => {
console.log('卸载完毕')
})
</script>
Hook
hook
? ————本质是一个函数,把setup
函数中使用的Composition API
进行了封装,类似与Vue2
中的mixin
hook
的优势:复用代码,让setup
中的逻辑更清楚易懂hooks
文件夹中,每一个功能的hook文件期望是usexxx
命名的composition API
的终极意义useSum.ts
中内容如下:import { ref, computed, onMounted } from 'vue'
export default function() {
let sum = ref(0)
let bigSum = computed(()=> {
return sum.value * 10
})
onMounted(()=> {
changeSum()
})
function changeSum(){
sum.value += 1
}
return {sum, bigSum, changeSum}
}
useDog.ts
中内容如下:import { reactive, onMounted } from 'vue'
import axios from 'axios'
export default function(){
let dogList = reactive([])
async function getDog(){
try{
let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
dogList.push(data.message)
} catch(error){
alert(error)
}
}
onMounted(() => {
getDog()
})
return {dogList, getDog}
}
<template>
<div>
<h2>当前值为{{ sum }}, 变大10倍的值是: {{ bigSum }}</h2>
<button @click="changeSum">点击加1</button>
<hr>
<img v-for="(dog,index) in dogList" :src="dog" :key="index" alt="">
<button @click="getDog">添加一只狗</button>
</div>
</template>
<script setup lang="ts">
import useSum from '@/hooks/useSum'
import useDog from '@/hooks/useDog'
let { sum, bigSum, changeSum } = useSum()
let { dogList, getDog } = useDog()
</script>
<style scoped>
img{
height: 150px;
margin-right: 10px;
}
</style>