vue2
<!--
* @Author: wangyf 1758985226@qq.com
* @Date: 2023-07-03 13:42:31
* @LastEditors: wangyf 1758985226@qq.com
* @LastEditTime: 2023-07-03 13:47:07
* @FilePath: \fast-vue3\src\pages\watch\index2.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AEmsg
-->
<template>
<div>
<input type="text" v-model="input" />
<input type="text" v-model="obj.name" />
</div>
</template>
<script>
export default {
data(){
retrun {
msg:'这是1',
obj:{
name:'王五'
}
}
},
watch:{
//初始化不监听msg的值
msg(newVal,oldVal){
console.log(newVal,oldVal)
},
// 初始化时就打印msg的值
msg:{
handler(newVal,oldVal){
console.log(newVal,oldVal)
},
immediate:true
},
// 深度监听
obj:{
handler(newVal,oldVal){
console.log(newVal,oldVal)
},
immediate:true,
deep:true,
}
}
}
</script>
<style></style>
vue3
<template>
<div>
<h1>watch</h1> <br />
<h1></h1><br />
<input type="text" />
<input v-model="msg" />
<input v-model="msg2" />
<input v-model="obj.name" />
<input v-model="obj.array" />
</div>
</template>
<script setup>
import { ref, watch, reactive, watchEffect } from 'vue';
const msg = ref('这是一个信息');
const msg2 = ref('这是2个信息');
const obj = reactive({
name: '123',
array: ['1', '2', '3'],
});
// 监听一个msg
watch(
msg,
(oldValue, newValue) => {
console.log(oldValue, newValue);
},
// 初始化的时候是否监听
{ immediate: true },
);
// 监听多个
watch(
[msg, msg2],
(newValue, oldValue) => {
console.log(oldValue, newValue);
},
{ immediate: true },
);
// 监听对象的某个属性
watch(
() => obj.array,
(newValue, oldValue) => {
console.log(newValue, oldValue);
},
);
// 监听多个
watch([msg, msg2, () => obj.array], (newValue, oldValue) => {
console.log(newValue, oldValue);
});
// 立即监听函数
watchEffect(() => {
console.log(msg.value);
});
</script>
<style></style>