×

vue3开发:watch和watchEffect

作者:Terry2021.02.05来源:Web前端之家浏览:5550评论:0
关键词:vuejsvue3

了解下在vue3中开发小应用:watch和watchEffect的使用区别。

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
 })

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/xuesandianling.html

网友评论文明上网理性发言 已有0人参与

发表评论: