文章目录
配置项的形式使用
用一个例子来学习 vue3 的生命周期钩子
App.vue 中引入 Demo,并添加一个按钮来隐藏或显示
<template>
<div>
<Demo v-if="isShow"/><br>
<button @click="isShow = !isShow">点我隐藏/显示</button>
</div>
</template>
<script>
import Demo from './components/Demo'
import {ref} from 'vue'
export default {
name: 'App',
components: {Demo},
setup(){
const isShow = ref(true)
return{
isShow
}
}
}
</script>
Demo 中显示一个 sum,点击按钮 sum++,同时我们把 vue3 中的生命周期钩子列出来,并打印
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">点我sum++</button>
</template>
<script>
import {ref} from 'vue'
export default {
name: 'Demo',
setup() {
let sum = ref(0);
return {
sum,
}
},
//通过配置项的形式使用生命周期钩子
beforeCreate() {
console.log("--beforeCreate");
},
created() {
console.log("--created");
},
beforeMount() {
console.log("--beforeMount");
},
mounted() {
console.log("--mounted");
},
beforeUpdate() {
console.log("--beforeUpdate");
},
updated() {
console.log("--updated");
},
beforeUnmount() {
console.log("--beforeUnmount");
},
unmounted() {
console.log("--unmounted");
}
}
</script>
刚一进页面:
当点击 sum++ 时:
当点击隐藏显示时:
隐藏后再点击展示:
组合式API形式使用
Vue3.0 中可以继续使用 Vue2.x中 的生命周期钩子,但有有两个被更名:
。beforeDestroy
改名为beforeUnmount
。destroyed
改名为unmounted
Vue3.0 也提供了 Composition AP I形式的生命周期钩子,与 Vue2.x 中钩子对应关系如下:
obeforeCreate
===>setup()
created
=======> setup()
beforeMount
===> onBeforeMount
mounted
=======> onMounted
beforeUpdate
===> onBeforeUpdate
updated
=======>onUpdated
beforeUnmount
==> onBeforeUnmount
unmounted
=====> onUnmounted
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">点我sum++</button>
</template>
<script>
import {onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref} from 'vue'
export default {
name: 'Demo',
setup() {
let sum = ref(0);
console.log("--setup");
onBeforeMount(() => {
console.log("--onBeforeMount");
})
onMounted(() => {
console.log("--onMounted");
})
onBeforeUpdate(() => {
console.log("--onBeforeUpdate");
})
onUpdated(() => {
console.log("--onUpdated");
})
onBeforeUnmount(() => {
console.log("--onBeforeUnmount");
})
onUnmounted(() => {
console.log("--onUnmounted");
})
return {
sum,
}
},
}
</script>
一进页面:
点 sum++
点击隐藏
点击显示