柳州网站建设之vue3 watch和watchEffect的使用以及有哪些区别 二维码
5
发表时间:2021-01-29 10:45 这篇文章主要介绍了vue3 watch和watchEffect的使用以及有哪些区别,帮助大家更好的理解和学习vue框架,感兴趣的朋友可以了解下 1.watch侦听器 引入watch import { ref, reactive, watch, toRefs } from 'vue' 对基本数据类型进行监听----- watch特性: 1.具有一定的惰性lazy **次页面展示的时候不会执行,只有数据变化的时候才会执行 2.参数可以拿到当前值和原始值 3.可以侦听多个数据的变化,用一个侦听起承载 setup() { const name = ref('leilei') watch(name, (curVal, prevVal) => { console.log(curVal, prevVal) }) } template: `Name: <input v-model="name" />` 对引用类型进行监听----- setup() { const nameObj = reactive({name: 'leilei', englishName: 'bob'}) 监听一个数据 watch(() => nameObj.name, (curVal, prevVal) => { console.log(curVal, prevVal) }) 监听多个数据 watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => { console.log(curName, curEng, '----', prevName, curEng) setTimeout(() => { stop1() }, 5000) }) const { name, englishName } = toRefs(nameObj) } template: `Name: <input v-model="name" /> englishName: <input v-model="englishName" />` 2.watchEffect 没有过多的参数 只有一个回调函数 1.立即执行,没有惰性,页面的首次加载就会执行。 2.自动检测内部代码,代码中有依赖 便会执行 3.不需要传递要侦听的内容 会自动感知代码依赖,不需要传递很多参数,只要传递一个回调函数 4.不能获取之前数据的值 只能获取当前值 5.一些=异步的操作放在这里会更加合适 watchEffect(() => { console.log(nameObj.name) }) 侦听器的取消 watch 取消侦听器用法相同 const stop = watchEffect(() => { console.log(nameObj.name) setTimeout(() => { stop() }, 5000) }) const stop1 = watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => { console.log(curName, curEng, '----', prevName, curEng) setTimeout(() => { stop1() }, 5000) }) watch也可以变为非惰性的 立即执行的 添加第三个参数 immediate: true watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => { console.log(curName, curEng, '----', prevName, curEng) setTimeout(() => { stop1() }, 5000) }, { immediate: true }) 以上就是vue3 watch和watchEffect的使用以及有哪些区别的详细内容 来源:https://www.jb51.net/article/204814.htm
文章分类:
技术文章
|