watchEffect
<template>
<div>
<input type="text" v-model="search.name1">
<input type="text" v-model="search.name2">
</div>
</template>
<script setup lang='ts'>
import { ref,watchEffect } from 'vue'
const search = ref({
name1:"aaa",
name2:"bbb"
})
watchEffect(() => {
// 侦听多个,把需要侦听的值放进去就可以
console.log("search1",search.value.name1)
console.log("search2",search.value.name2)
})
</script>
<style scoped>
</style>
watchEffect 清除副作用
<template>
<div>
<input type="text" v-model="search.name1">
<input type="text" v-model="search.name2">
</div>
</template>
<script setup lang='ts'>
import { ref,watchEffect } from 'vue'
const search = ref({
name1:"aaa",
name2:"bbb"
})
watchEffect((oninalidata) => {
// 侦听多个,把需要侦听的值放进去就可以
console.log("search1",search.value.name1)
console.log("search2",search.value.name2)
oninalidata(() => {
console.log("before")
})
})
</script>
<style scoped>
</style>
做一个例子,比如我们关闭页面的时候,想要停止请求,或者停止侦听,我们就可以用这种方法去实现,当我们点击停止侦听的时候,就会不再侦听
<template>
<div>
<input type="text" v-model="search.name1">
<input type="text" v-model="search.name2">
<button @click="stopWatch">stopWatch</button>
</div>
</template>
<script setup lang='ts'>
import { ref,watchEffect } from 'vue'
const search = ref({
name1:"aaa",
name2:"bbb"
})
const stop = watchEffect((oninalidata) => {
// 侦听多个,把需要侦听的值放进去就可以
console.log("search1",search.value.name1)
console.log("search2",search.value.name2)
oninalidata(() => {
console.log("before")
})
})
const stopWatch = () => stop()
</script>
<style scoped>
</style>
<template>
<div>
<input type="text" id="iput" v-model="search.name1">
</div>
</template>
<script setup lang='ts'>
import { ref,watchEffect } from 'vue'
const search = ref({
name1:"aaa",
name2:"bbb"
})
watchEffect((oninalidata) => {
let iput:HTMLInputElement = document.querySelector('#iput') as HTMLInputElement
console.log(iput)
// 侦听多个,把需要侦听的值放进去就可以
console.log("search1",search.value.name1)
console.log("search2",search.value.name2)
oninalidata(() => {
console.log("before")
})
},{
flush:"post", // 组件更新后执行
// flush:"pre" // 组件更新前执行
// flush:"sync" // 强制效果始终同步触发
// 还提供了一个调试的api
onTrigger(e) {
// 这个时候我们可通过对象看到数据是否发生变化
console.log(e)
}
})
</script>
<style scoped>
</style>