watch的用法,没成功

本文通过三个示例探讨了Vue.js中的ref和watch用法。第一个例子展示了如何在模板中使用button点击改变counter值,并通过watch监听变化。第二个例子错误地尝试将counter的值设为字符串,导致类型错误。第三个例子中,尝试直接在模板中使用counter++,但这种方式不会触发watch监听。总结了在Vue中正确管理和更新响应式属性的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div>
    <button @click="changeCounter">确认</button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const counter = ref(0)
//counter.value++ 
const changeCounter = () => { 
  counter.value++
}

watch(counter, (newValue, oldValue) => {
  console.log('The new counter value is: ' + counter.value)
  console.log("new counter======{}==",newValue);
  console.log("old counter======{}==",oldValue);
})

return {
      counter,
      changeCounter
    }
</script>

错误

<template>
  <div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const counter = ref(0)
counter.value = '5'
watch(counter, (newValue, oldValue) => {
  console.log('The new counter value is: ' + counter.value)
})

</script>



这个为啥不行?

<template>
  <div id="app">
    <p>计数器:{{ counter }}</p>
    <el-button type="primary" @click="counter++">
      Click
    </el-button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
  const counter = ref(0)
  watch(counter, (newValue, oldValue) => {
   console.log('The new counter value is: ' + counter.value)
})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值