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>
相关推荐
森林的尽头是阳光5 分钟前
tree回显问题
javascript·vue.js·elementui
weixin_BYSJ198726 分钟前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
Highcharts.js1 小时前
如何下载使用Highcharts Grid 开发web可编辑表格
前端·人工智能·grid 表格·web 表格·在线编辑表格·highcharts表格安装·表格开发工具
用户62960593247051 小时前
从“浏览器根本区分不了”到真正实现:刷新不退出,关闭标签页自动退出,前端判断浏览器关闭和刷新
前端
qetfw1 小时前
MWU:Vue 3 + FastAPI 的 MaaFramework 跨平台 WebUI 源码
前端·vue.js·python·fastapi·开源项目·效率工具
mfxcyh1 小时前
Vue3+Ant Design Vue 实现手动异步文件上传(含大小校验、弹窗上传)
前端·javascript·vue.js
wordbaby1 小时前
Web端热敏标签打印完整解决方案(QZ Tray + 译维A42)
前端
swipe2 小时前
03|Axios 请求进了后端之后:Controller、Request、Response 是怎么接住它的?
前端·后端·全栈
meilindehuzi_a2 小时前
Vue3进阶基础:指令修饰符、v-model表单绑定、动态样式、计算属性与侦听器实战
前端·javascript·vue.js
csdn2015_2 小时前
vue 前端运行命令
前端·javascript·vue.js