Vue基础(3)监听数据

1. 监听 ref

<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 函数。

<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 时,监听器会进行深度监听。即当监听的数据源(对象或数组)内部的属性值发生变化时,监听器也会触发回调函数。
<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 时,监听器会在初始化时立即执行一次回调函数,即不需要等待被监听的数据源发生变化。
<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 不需要明确指定要监听的数据源,它会立刻执行一次函数,并自动跟踪该函数中使用的所有响应式引用和计算属性,当它们变化时重新运行该函数。

watchEffect( () => {
  console.log(count.value)
})
  • 18
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值