watch 监听器
js
<template>
<div>
值 : {{ x }}
<button @click="changX">点击</button>
</div>
</template>
<script setup>
import { ref,watch } from 'vue'
const x = ref(0)
const changX=()=> {
x.value += 1
}
watch(x,(newValue,OldValue)=>{
console.log('x的变化',newValue, OldValue);
},{deep:true,immediate:true}) //深度监听 和立刻监听
</script>
<style lang="scss" scoped></style><template>
<div>
值 : {{ x }}
<button @click="changX">点击</button>
</div>
</template>
<script setup>
import { ref,watch } from 'vue'
const x = ref(0)
const changX=()=> {
x.value += 1
}
watch(x,(newValue,OldValue)=>{
console.log('x的变化',newValue, OldValue);
},{deep:true,immediate:true}) //深度监听 和立刻监听
</script>
<style lang="scss" scoped></style>DANGER
推荐用法 函数式写法 官方推荐
js
// 推荐用法、
watch(()=>x,(newValue,OldValue)=>{
console.log('x的变化',newValue, OldValue);
},{deep:true})// 推荐用法、
watch(()=>x,(newValue,OldValue)=>{
console.log('x的变化',newValue, OldValue);
},{deep:true})
zuolingfeng