Vue基础(3)监听数据

1. 监听 ref

xml 复制代码
<script setup>
import { ref, watch} from 'vue'

const count = ref(0)
watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`)
})
</script>

<template>
  <button @click="count++">{{ count }}</button> 
</template>

2. 监听 reactive

不能直接监听响应式对象的属性值,而是需要用一个返回该属性的 getter 函数。

xml 复制代码
<script setup>
import { reactive, watch} from 'vue'

const state = reactive({count: 0})
watch(() => state.count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`)
})
</script>

<template>
  <button @click="state.count++">{{ state.count }}</button> 
</template>

3. 可选配置对象

  • deep:当设置为 true 时,监听器会进行深度监听。即当监听的数据源(对象或数组)内部的属性值发生变化时,监听器也会触发回调函数。
xml 复制代码
<script setup>
import { reactive, watch} from 'vue'

const state = reactive({good: {count: 2, price: 20}})
watch(() =>state.good, (newValue, oldValue) => {		// newValue和oldValue相同
	console.log(`count changed from ${oldValue.count } to ${newValue.count}`)	// 点击之后打印'from 3 to 3'
}, {deep: true})	// 没有配置deep: true时,点击count变化但是没有打印日志
</script>

<template>
  <span>{{ state.good }}</span>
  <button @click="state.good.count++">+</button> 
</template>
  • immediate:当设置为 true 时,监听器会在初始化时立即执行一次回调函数,即不需要等待被监听的数据源发生变化。
xml 复制代码
<script setup>
import { reactive, watch} from 'vue'

const state = reactive({good: {count: 2, price: 20}})
watch(() =>state.good, (newValue, oldValue) => {		
	console.log(newValue)		// Proxy(Object) {count: 2, price: 20}
	console.log(oldValue)		// undefined
}, {immediate: true})	 // 初始化时打印一次
</script>

<template>
  <span>{{ state.good }}</span>
  <button @click="state.good.count++">+</button> 
</template>
  • once:当设置为 true 时,监听器只会在第一次数据变动时触发回调函数,之后即使被监听的数据源再次发生变化,也不会再次触发回调函数。

4. watchEffect

与 watch 相比,watchEffect 不需要明确指定要监听的数据源,它会立刻执行一次函数,并自动跟踪该函数中使用的所有响应式引用和计算属性,当它们变化时重新运行该函数。

js 复制代码
watchEffect( () => {
  console.log(count.value)
})
相关推荐
崔庆才丨静觅3 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60614 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅4 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅5 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅5 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊5 小时前
jwt介绍
前端
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax