您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

vue3中watch和watchEffect使用实例分析

2024/3/28 20:46:44发布4次查看
watchwatch监听单个数据<template> <input type="text" v-model="text1" /></template><script setup>import { ref, watch } from 'vue'const text1 = ref('')watch(text1, (newval, oldval) => { console.log('监听单个数据', newval, oldval)})</script>
watch监听多个数据<template> <input type="text" v-model="text1" /> <input type="text" v-model="text2" /></template><script setup>import { ref, watch } from 'vue'const text1 = ref('')const text2 = ref('')watch([text1, text2], (newval, oldval) => { console.log('监听一组数据', newval, oldval)})</script>
watch监听对象<template> name: <input type="text" v-model="student.name" /> age: <input type="number" v-model="student.age" /></template><script setup>import { reactive, watch } from 'vue'const student = reactive({ name: '', age: ''})watch(student, (newval, oldval) => { console.log('newval', newval) console.log('oldval', newval)})</script>
watch还有第三个参数,deep和immediate,可以加上看看效果
watch监听对象的某一个值<template> name: <input type="text" v-model="student.name" /> age: <input type="number" v-model="student.age" /></template><script lang="ts" setup>import { reactive, watch } from 'vue'const student = reactive({ name: '', age: ''})watch(() => student.name, (newval, oldval) => { console.log('newval', newval) console.log('oldval', newval)}, { deep: true, immediate: true})</script>
监听对象某一个属性的时候需要用箭头函数
watcheffect关于watcheffect,官网是这么介绍的:为了根据响应式状态自动应用和重新应用副作用,我们可以使用watcheffect方法,它立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。 也就是说,我们并不需要传入一个特定的依赖源,而且它会立即执行一遍回调函数,如果函数产生了副作用,那它就会自动追踪副作用的依赖关系,自动分析出响应源。光看概念可能比较模糊,先来看个最简单的例子:
<template> name: <input type="text" v-model="student.name" /> age: <input type="number" v-model="student.age" /></template><script lang="ts" setup>import { reactive, watcheffect } from 'vue'const student = reactive({ name: '', age: ''})watcheffect(() => { console.log('name: ',student.name, 'age: ', student.age)})</script>
watcheffect副作用副作用,那什么是副作用呢,其实很简单,就是在监听之前,我得做一件事。
<template> name: <input type="text" v-model="student.name" /> age: <input type="number" v-model="student.age" /> <h3>{{student.name}}</h3></template><script lang="ts" setup>import { reactive, watcheffect } from 'vue'const student = reactive({ name: '', age: ''})watcheffect((oninvalidate) => { oninvalidate(() => { student.name = '张三' }) console.log('name: ', student.name)}, { // pre 组件更新前; sync:强制效果始终同步; post:组件更新后执行 flush: 'post' // dom加载完毕后执行})</script>
监听之前让student.name赋值为'张三',无论你输入什么值,name一直都是'张三'
停止监听我们用同步语句创建的监听器,会自动绑定到组件实例上,并且会在组件卸载时自动停止,但是,如果我们在异步回调里创建一个监听器,那它就不会绑定到当前组件上,必须手动去停止,防止内存泄漏。 那怎么去停止呢,其实我们只需要调用一下watch或watcheffect返回的函数
const stop = watcheffect(() => {})// 停止监听unwatch()
区别用了一遍watch和watcheffect之后,发现他俩主要有以下几点区别:
watch是惰性执行的,而watcheffect不是,不考虑watch第三个配置参数的情况下,watch在组件第一次执行的时候是不会执行的,只有在之后依赖项变化的时候再执行,而watcheffect是在程序执行到此处的时候就会立即执行,而后再响应其依赖变化执行。
watch需要传递监听的对象,watcheffect不需要
以上就是vue3中watch和watcheffect使用实例分析的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录