setup()中使用watch,先从 Vue对象中解构赋值得到 watch,然后使用
// 获得watch
const { watch } = Vue
可以使用 watch 来侦听数据的变化,获得它的 当前值 和 原来值
watch 是懒加载(lazy),首次打开页面时,不会执行,当被侦听的元素内容发生改变后才会触发执行
// 使用watch
watch(变量名, (当前值, 原来值) => {
// 内容
})
eg:
watch(() => obj.属性名, (当前值, 原来值) => {
// 内容
})
watch也可以侦听多个字段,参数值以数组形式传递:
watch([字段1, 字段2], ([字段1当前值, 字段2当前值], [ 字段1原来值, 字段2原来值]) => {
// 内容
})
以上为侦听两个字段,侦听更多个字段依次类推
例如侦听两个字段- - -title, users:
watch([title, users], ([curTitle, curUsers], [ preTitle, preUsers]) => {
console.log(curTitle, preTitle, '---', curUsers, preUsers)
})
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>watch侦听器title>
<script src="https://unpkg.com/vue@next">script>
head>
<body>
<div id="root">div>
body>
<script>
const app = Vue.createApp({
setup() {
const { ref, watch } = Vue
const title = ref('国王排名')
watch(title, (curTitle, preTitle) => {
console.log(curTitle, preTitle)
})
return { title }
},
template: `
片名:
片名: {{title}}
`
})
const vm = app.mount('#root')
script>
html>
输入内容修改后侦听到改变,输入结果:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>watch侦听器title>
<script src="https://unpkg.com/vue@next">script>
head>
<body>
<div id="root">div>
body>
<script>
const app = Vue.createApp({
setup() {
const { reactive, watch, toRefs } = Vue
const obj = reactive({title: '教父'})
watch(() => obj.title, (curTitle, preTitle) => {
console.log(curTitle, preTitle)
})
const { title } = toRefs(obj)
return { title }
},
template: `
片名:
片名: {{title}}
`
})
const vm = app.mount('#root')
script>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>watch侦听器title>
<script src="https://unpkg.com/vue@next">script>
head>
<body>
<div id="root">div>
body>
<script>
const app = Vue.createApp({
setup() {
const { ref, watch } = Vue
const title = ref('国王排名')
const users = ref('波吉')
watch([title, users], ([curTitle, curUsers], [ preTitle, preUsers]) => {
console.log(curTitle, preTitle, '---', curUsers, preUsers)
})
return { title, users }
},
template: `
片名:
人物:
`
})
const vm = app.mount('#root')
script>
html>
同时侦听两个字段,只要修改了其中的字段就触发watch,记录两个字段的当前、原来值
watch还可以接受第三个参数,第三个参数中进行配置管理,可以更改原来默认的懒加载模式,添加第三个参数- - -{immediate: true}
watch(要侦听的字段, (当前值, 原来值) => {
// 回调函数内容
}, {immediate: true})
设置后,首次加载页面也会执行watch,以上示例中修改watch代码如下:
watch([title, users], ([curTitle, curUsers], [ preTitle, preUsers]) => {
console.log(curTitle, preTitle, '---', curUsers, preUsers)
}, {immediate: true})
return { title, users }
修改后,首次打开页面,控制台也会打印结果,效果如下:
const testWatch = watch(侦听字段名, (当前值, 原来值) {
// 回调函数内容
setTimeout(() => {
testWatch()
}, 时长)
})