一般情况下属性都是直接定义的,但是有些属性可能是需要经过一些逻辑计算后才能得出来,那么我们可以把这类属性变成计算属性。比如以下:
<script setup>
import {ref, computed} from "vue";
let width = ref(0);
let height = ref(0);
let area = computed(() => {
return width.value*height.value;
})
</script>
<template>
<label for="length">长:</label>
<input type="number" name="height" v-model="height">
<label for="width">宽:</label>
<input type="number" name="width" v-model="width">
<label for="area">面积:</label>
<input type="number" name="area" :value="area" readonly>
</template>
属性监听功能允许我们实时追踪属性值的变化。一旦属性值发生改变,我们可以通过相关函数立即获取到新的值。根据定义属性的方法的不同,属性监听主要分为两种情况:一种是针对使用ref函数定义的属性,另一种是针对使用reactive函数定义的属性。
对于使用ref函数定义的基本数据类型,则直接监听即可,示例代码如下:
<script setup>
import {ref, watch} from "vue";
let width = ref(0);
watch(width, (newValue, oldValue) => {
console.log(newValue);
})
const onUpdateWidth = () => {
width += 1;
}
</script>
<template>
<div>
<p>宽度:{{ width }}</p>
<button @click="onUpdateWidth">修改width</button>
</div>
</template>
而对于使用ref函数定义的对象类型,如果要监听整个对象的变化,则直接监听即可:
<script setup>
import {ref, watch} from "vue";
let person = ref({
username: '张三',
age: 18
})
const onUpdatePerson = () => {
person.value = {'username': '李四', "age": 20};
}
watch(person, (newValue, oldValue) => {
console.log(newValue);
})
</script>
<template>
<div>
<p>用户名:{{ person.username }},年龄:{{ person.age }}</p>
<button @click="onUpdatePerson">修改person</button>
</div>
</template>
如果要监听属性下的子属性的变化,要么通过getter函数监听某个子属性,或者开启深度监听,监听所有子属性的变化:
<script setup>
import {ref, watch} from "vue";
let person = ref({
username: '张三',
age: 18
})
const onUpdateUsername = () => {
person.value.username += "1"
}
const onUpdateAge = () => {
person.value.age += 1
}
// 监听某个子属性的变化,使用getter方法
watch(() => person.value.username, (newValue, oldValue) => {
console.log("new username: ", newValue);
})
// 监听整个对象子属性的变化,开启深度监听
watch(person, (newValue, oldValue) => {
console.log("new person: ", newValue);
}, {deep: true})
</script>
<template>
<div>
<p>用户名:{{ person.username }},年龄:{{ person.age }}</p>
<button @click="onUpdateUsername">修改username</button>
<button @click="onUpdateAge">修改age</button>
</div>
</template>
对于使用reactive函数定义的属性,那么默认会开启深度监听,所以不管是监听一个子属性的变化,还是监听所有子属性的变化,都无需手动开启深度监听。示例代码如下:
<script setup>
import {ref, reactive, watch} from "vue";
let university = reactive({
name: '清华大学',
year: 1911
})
const updateUniversityName = () => {
university.name = '北京大学'
}
// 1. 监听一个子属性的变化
watch(() => univertisy.name, (newValue, oldValue) => {
console.log('new name: ', newValue);
})
// 2. 监听所有子属性的变化
watch(university, (newValue, oldValue) => {
console.log(newValue);
})
</script>
<template>
<div>
<div>大学名称:{{ university.name }}</div>
<button @click="updateUniversityName">更换大学名称</button>
</div>
</template>