学习Vue3 第十章(认识watch侦听器)

简介: watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用

watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用


watch第一个参数监听源


watch第二个参数回调函数cb(newVal,oldVal)


watch第三个参数一个options配置项是一个对象{


immediate:true //是否立即调用一次


deep:true //是否开启深度监听


}


监听Ref 案例


import { ref, watch } from 'vue'
let message = ref({
    nav:{
        bar:{
            name:""
        }
    }
})
watch(message, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
},{
    immediate:true,
    deep:true
})


监听多个ref 注意变成数组啦


import { ref, watch ,reactive} from 'vue'
let message = ref('')
let message2 = ref('')
watch([message,message2], (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})


监听Reactive


使用reactive监听深层对象开启和不开启deep 效果一样


import { ref, watch ,reactive} from 'vue'
let message = reactive({
    nav:{
        bar:{
            name:""
        }
    }
})
watch(message, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})


案例2 监听reactive 单一值


import { ref, watch ,reactive} from 'vue'
let message = reactive({
    name:"",
    name2:""
})
watch(()=>message.name, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})


目录
相关文章
|
1天前
|
JavaScript API UED
Vue3中的Suspense组件有什么用?
Vue3中的Suspense组件有什么用?
16 6
|
1天前
|
JavaScript 前端开发 索引
Vue3基础之v-if条件与 v-for循环
Vue3基础之v-if条件与 v-for循环
6 0
|
1天前
|
JavaScript
Vue3基础之v-bind与v-on
Vue3基础之v-bind与v-on
9 0
|
1天前
|
JavaScript 测试技术 API
Vue3中定义变量是选择ref还是reactive?
Vue3中定义变量是选择ref还是reactive?
12 2
|
1天前
|
移动开发 前端开发
ruoyi-nbcio-plus基于vue3的flowable为了适配文件上传改造VForm3的代码记录
ruoyi-nbcio-plus基于vue3的flowable为了适配文件上传改造VForm3的代码记录
17 1
|
1天前
|
JavaScript 前端开发
vue2升级到vue3的一些使用注意事项记录(四)
vue2升级到vue3的一些使用注意事项记录(四)
12 0
|
1天前
|
移动开发 前端开发
ruoyi-nbcio-plus基于vue3的flowable收回任务后重新进行提交表单的处理
ruoyi-nbcio-plus基于vue3的flowable收回任务后重新进行提交表单的处理
13 0
|
1天前
|
JavaScript
VUE里的find与filter使用与区别
VUE里的find与filter使用与区别
22 0
|
1天前
|
JavaScript
vue页面加载时同时请求两个接口
vue页面加载时同时请求两个接口
|
1天前
|
JavaScript
vue里样式不起作用的方法,可以通过deep穿透的方式
vue里样式不起作用的方法,可以通过deep穿透的方式
14 0