Vue 3中常用的生命周期钩子和监听器的详细分析

目录

  • 前言
  • [1. onMounted](#1. onMounted)
  • [2. watch](#2. watch)
  • [3. computed](#3. computed)
  • [4. 其他](#4. 其他)

前言

分析常用的一些生命周期钩子和监听器可以帮助我们在组件中处理数据加载、状态变化和响应式更新

1. onMounted

生命周期钩子,在组件挂载后执行。它适合用于初始化数据加载或执行一次性的操作

html 复制代码
<template>
  <div>
    <p>当前用户ID: {{ userId }}</p>
    <button @click="fetchUserData">加载用户数据</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import UserDataApi from 'path-to-your-api'; // 假设这是你的数据接口

const userId = ref(null);
const userData = ref(null);

onMounted(async () => {
  // 初始化加载数据
  await fetchUserData();
});

const fetchUserData = async () => {
  const response = await UserDataApi.getUserData();
  userId.value = response.userId;
  userData.value = response.userData;
};
</script>

2. watch

监听指定的响应式数据,并在数据变化时执行回调函数

有两种形式:基础的 watch 和 watchEffect

html 复制代码
<template>
  <div>
    <p>当前计数: {{ count }}</p>
    <button @click="increment">增加计数</button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`计数从 ${oldValue} 变为 ${newValue}`);
});
  
const increment = () => {
  count.value++;
};
</script>

watchEffect 在其依赖变化时立即执行传入的回调函数

html 复制代码
<template>
  <div>
    <p>当前时间: {{ currentTime }}</p>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue';

const currentTime = ref(new Date());

watchEffect(() => {
  console.log('更新当前时间');
  currentTime.value = new Date();
});

// 模拟定时更新时间
setInterval(() => {
  currentTime.value = new Date();
}, 1000);
</script>

3. computed

computed: 计算属性,基于响应式数据派生出新的数据,并自动缓存结果

html 复制代码
<template>
  <div>
    <p>原始数值: {{ originalValue }}</p>
    <p>加倍后的值: {{ doubledValue }}</p>
    <button @click="increment">增加数值</button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const originalValue = ref(5);

const doubledValue = computed(() => originalValue.value * 2);

const increment = () => {
  originalValue.value++;
};
</script>

4. 其他

reactive: 创建一个完全响应式的对象或数组

html 复制代码
<template>
  <div>
    <p>当前用户: {{ user.name }}</p>
    <button @click="changeUserName">修改用户名</button>
  </div>
</template>

<script setup>
import { reactive } from 'vue';

const user = reactive({
  name: 'John Doe',
  age: 30
});

const changeUserName = () => {
  user.name = 'Jane Smith';
};
</script>

ref: 创建一个响应式的引用,通常用于包装基本类型值

html 复制代码
<template>
  <div>
    <p>当前计数: {{ count.value }}</p>
    <button @click="increment">增加计数</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>
相关推荐
橙序员小站1 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名4 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫4 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊4 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter4 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折4 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_4 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码15 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial5 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu5 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端