<template>
<div>
<h1>reactive定义的数据</h1>
<h2>当前求和为:{{data.count}}</h2>
<h2>当前求和为:{{data.num}}</h2>
<h2>当前薪资:{{data.job.salary}}</h2>
<button @click="handleCount">count+1</button>
<button @click="handleCount2">num+1</button>
<button @click="handleCount5">修改薪资</button>
<hr>
<h1>ref定义的数据</h1>
<h2>sum:{{sum}}</h2>
<h2>msg:{{msg}}</h2>
<button @click="handleCount3">sum+1</button>
<button @click="handleCount4">msg+!</button>
</div>
</template>
<script>
import {reactive,watch,ref} from 'vue';
export default {
// vue2中的watch监听数据:vue2中监听对象类型的数据时,需要开启深度监视
watch:{
data:{
// deep:true,
// immediate:true,//设置这个配置项,页面一刷新handler函数就会自动被调用一遍
handler:function(){ // handler名称是固定的
console.log("data.count数据发生变化");
}
}
},
setup(props) {
let data=reactive({
count:0,
num:1,
job:{
salary:"20k"
}
})
let sum=ref(0)
let msg=ref("hello")
// vue3中的watch是一个组合式API,【组合式API其实就是Vue封装的一些函数】
// watch(监视的数据,回调函数,【{deep:true,immedate:true}】) // deep在vue3中有点问题
// 监视用法一: 监视ref定义的数据,监听单个ref的数据变化
watch(sum,(newVal,oldVal)=>{
console.log("数据发生变化");
console.log(newVal,oldVal);
})
// 监视用法二:监视ref定义的多个数据,任意一个数据发生变化就会触发第二个参数【触发回调函数】
watch([sum,msg],(newVal,oldVal)=>{
console.log("数据发生变化");
console.log(newVal,oldVal); // 两个参数变为数组
})
// 监视用法三:监视reactive定义全部数据【深度监视】,watch监听的reactive的数据,无法获取到oldVal;watch监听的reactive的数据强制开启了深度监视
watch(data,(newVal,oldVal)=>{
console.log(newVal,oldVal); // newVal=oldVal
},{deep:false}) // 此处的deep配置无效
// 监视用法四:监视reactive定义的某一个属性
// watch(函数的返回值就是watch监听的数据,回调函数)
watch(()=>data.count,(newVal,oldVal)=>{
console.log("data中的count数据发生变化",newVal,oldVal);
})
// 监视用法五:监视reactive定义的数据的某些属性
watch([()=>data.count,()=>data.num],(newVal,oldVal)=>{
console.log("data中的count或num数据发生变化",newVal,oldVal);
})
// 特殊情况:监听reactive定义的深层的单个属性对象时,需要借助第三个参数{deep:true}开启深度监视
watch(()=>data.job,(newVal,oldVal)=>{
console.log("data中的salary数据发生变化",newVal,oldVal);
},{deep:true})
function handleCount(){
data.count+=1
}
function handleCount2(){
data.num+=1
}
function handleCount3(){
// console.log(sum);
sum.value+=1
}
function handleCount4(){
msg.value+="!"
}
function handleCount5(){
data.job.salary+="~"
}
return {
data,
sum,
msg,
handleCount,
handleCount2,
handleCount3,
handleCount4,
handleCount5
}
}
}
</script>
<style>
</style>
Vue2与Vue3数据监听 Vue watch的使用
最新推荐文章于 2024-05-24 09:05:58 发布