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

前言

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

1. onMounted

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

<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

<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 在其依赖变化时立即执行传入的回调函数

<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: 计算属性,基于响应式数据派生出新的数据,并自动缓存结果

<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: 创建一个完全响应式的对象或数组

<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: 创建一个响应式的引用,通常用于包装基本类型值

<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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值