0
点赞
收藏
分享

微信扫一扫

【vue-8】记事本案例

boomwu 2024-06-13 阅读 3

文章目录


前言

每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。
在这里插入图片描述


一、生命周期

1. 两大类

  • 选项式 API
  • 组合式 API

两类生命周期用法不同,作用是一样的。

2. 生命周期

  1. beforeCreate

  2. created

  3. beforeMount

  4. mounted

  5. beforeUpdate

  6. updated

  7. beforeUnmount

  8. unmounted

二、选项式生命周期

1. 代码

<!-- 选项式 API -->
<script>
export default {
  data() {
    return {
        msg: '北京',
        count: 0
    };
  },
  beforeCreate() {
    console.log('the component is now before create.')
  },
  created() {  
    console.log('the component is now created.')
  },
  beforeMount() {
    console.log('the component is now before mount.')
  },
  mounted() {  
    console.log('the component is now mounted.')
  },
  beforeUpdate() {
    console.log('the component is now before update.')
  },
  updated() {  
    console.log('the component is now updated.')
  },
  beforeUnmount() {
    console.log('the component is now before unmount.')
  },
  unmounted() {  
    console.log('the component is now unmounted.')
  }
};
</script>
<template>
  <h2>{{ msg }},欢迎你</h2><br>
  <button id="count" @click="count++">{{ count }}</button>
</template>

<style>
  h2{
    color:red;
  }
</style>

2. 效果

在这里插入图片描述

三、组合式生命周期

1. 代码

<script setup>
import { ref,onBeforeMount,onMounted,onBeforeUpdate, onUpdated,onBeforeUnmount,onUnmounted } from 'vue'
const msg=ref('北京')
onBeforeMount(() => {
  console.log(`the component is now before mounted.`)
})
onMounted(() => {
  console.log(`the component is now mounted.`)
})
const count = ref(0)
onBeforeUpdate(() => {
  console.log(`the component is now before updated.`)
})
onUpdated(() => {
  console.log(`the component is now updated.`)
})
onBeforeUnmount(() => {
  console.log(`the component is now before unmount.`)
})
onUnmounted(() => {
  console.log(`the component is now unmounted.`)
})
</script>

<template>
  <h1>{{ msg }},欢迎你</h1><br>
  <button id="count" @click="count++">{{ count }}</button>
</template>

<style>
  h1{
    color:red;
  }
</style>

2. 效果

2.1 挂载和更新

在这里插入图片描述

2.2 卸载和挂载

在这里插入图片描述


总结

回到顶部

举报

相关推荐

0 条评论