vue3之生命周期
组件被创建时,一定调用的两个hock函数
- onBeforeMount 与 onMounted
- 组件挂载前,组件挂载后(dom节点渲染完毕了,可操作dom节点等,也可以进行数据的请求)
<template>
<div>
</div>
</template>
<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
console.log('setup')
onBeforeMount(() => {
console.log('组件挂载前onBeforeMount')
})
onMounted(() => {
console.log('组件挂载后onMounted')
})
</script>
<style lang="scss" scoped></style>
- 效果
组件内的值更新后,会触发的两个hock函数
- onBeforeUpdate 与 onUpdated
- 再组件内部的数据发生变化的时候,就会触发以上两个hock函数
<template>
<div>
我是num -- {{ num }}
<button @click="num++">修改num</button>
</div>
</template>
<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
let num = ref<Number>(0)
onBeforeUpdate(() => {
console.log('组件更新前onBeforeUpdate')
})
onUpdated(() => {
console.log('组件更新后onUpdated')
})
</script>
<style lang="scss" scoped></style>
- 效果
组件被销毁时,会触发两个hock函数
<template>
<div>
我是num -- {{ num }}
<button @click="num++">修改num</button>
</div>
</template>
<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
console.log('setup')
let num = ref<Number>(0)
onBeforeMount(() => {
console.log('组件挂载前onBeforeMount')
})
onMounted(() => {
console.log('组件挂载后onMounted')
})
onBeforeUpdate(() => {
console.log('组件更新前onBeforeUpdate')
})
onUpdated(() => {
console.log('组件更新后onUpdated')
})
onBeforeUnmount(() => {
console.log('组件销毁前onBeforeUnmount')
})
onUnmounted(() => {
console.log('组件销毁后onUnmounted')
})
</script>
<style lang="scss" scoped></style>
<template>
<div style="height: 50px">2</div>
<button @click="flag = !flag">控制 hellw组件</button>
flag值 {{ flag }}
<HelloWorld v-if="flag" msg="Hello Vue 3 + TypeScript + Vite" />
</template>
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
import { ref } from 'vue'
let flag = ref<Boolean>(true)
</script>
|