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>
相关推荐
mCell6 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip6 小时前
Node.js 子进程:child_process
前端·javascript
excel9 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel10 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼11 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping11 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙12 小时前
[译] Composition in CSS
前端·css
白水清风12 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix12 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780012 小时前
new、原型和原型链浅析
前端·javascript