<template>
<el-form :inline="true" :model="formInline" class="demo-form-inline">
<el-form-item label="Approved by">
<el-input v-model="formInline.user" placeholder="Approved by" clearable />
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="formInline.region" placeholder="Activity zone" clearable>
<el-option label="Zone one" value="shanghai" />
<el-option label="Zone two" value="beijing" />
</el-select>
</el-form-item>
<el-form-item label="Activity time">
<el-date-picker v-model="formInline.date" type="date" placeholder="Pick a date" clearable />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">Query</el-button>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { reactive, watch, ref } from 'vue'
const formInline = reactive({
user: '',
region: '',
date: '',
})
const onSubmit = () => {
console.log('submit!')
}
let sum = ref(2)
//watch监听 ref定义基本类型
// 1---------111
watch(sum, (newValue, oldValue) => {
})
//watch监听 ref定义的对象
// 2---------222
let person = ref({
name: "zhang",
age: 23
})
const changeAge = () => {
person.value.age += 1
}
/*
监视对象地址
watch的第一个参数是:被监视的数据
watch的第二个参数是:监视的回调
watch的第三个参数是:配置对象(deep、immediate)
*/
watch(person, (newValue, oldValue) => {
console.log(newValue, oldValue, 21212)
}, { deep: true, immediate: true })
/*
3------3333
第三种情况
监听【reactive】定义的对象类型数据,默认是开启深度监听的 并且深度监听无法关闭深度监听
*/
let person123 = reactive({
name: "zhang",
age: 23
})
const changeName = () => {
// 整体改变reactive定义的对象
Object.assign(person123, { name: "2323", age: 30 })
}
watch(person123, (newValue, oldValue) => {
console.log(newValue, oldValue, 231213222)
})
/*
4-----44444
监听【reactive】定义数据,监视响应式里面的某一个值
使用 箭头函数 ()=>{return return personDemo.name }
*/
let personDemo = reactive({
name: "zhang",
age: 23,
car: {
price: 232,
type: '雅迪'
}
})
watch(() => { return personDemo.name }, (newValue, oldValue) => {
console.log(newValue, oldValue, 231213222)
})
/*
监视的要是对象里的属性,可以直接编:personDemo.car
也可写成函数,建议写成函数:() => personDemo.car
监视要是对象属性,最好写成函数式,
注意点,若是对象监视的是地址值(),需要关注对象内部需要手动开启深度监听 { deep: true }
*/
watch(() => personDemo.car, (newValue, oldValue) => {
console.log(newValue, oldValue, 231213222)
}, { deep: true })
/*
5-------------5555555
监视多个数据
*/
watch([() => personDemo.name,() => personDemo.car.type], (newValue, oldValue) => {
console.log(newValue, oldValue, 231213222)
}, { deep: true })
</script>
<style>
.demo-form-inline .el-input {
--el-input-width: 220px;
}
.demo-form-inline .el-select {
--el-select-width: 220px;
}
</style>
vue3 watch监听5种使用方法
于 2024-10-01 17:28:27 首次发布