一,computed
用法一:传入一个getter函数
setup() {
const firstName = ref('李')
const lastName = ref('华')
// 传入一个getter函数
const fullName = computed(() => firstName.vaule + lastName.value);
}
用法二:传入一个对象,对象包含getter/setter
setup() {
const firstName = ref('李')
const lastName = ref('华')
const fullName = computed({
get: () => firstName.value + lastName.value,
set(newVaule) {
// 这里可以写一些处理逻辑
}
})
}
二、watchEffect
当我们需要监听数据的变化时,可以使用watchEffect
- watchEffect在代码第一次执行的时候会立即执行一次,并且会去收集依赖;
- 只有收集的依赖发生变化时,watchEffect传入的函数才会再次执行;
1.使用方式
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const name = ref("zhangsan");
const age = ref(20);
const changeName = () => name.value = "lisi"
const changeAge = () => age.value++
// watchEffect: 自动收集响应式的依赖,watchEffect只收集到了name属性,所以当name的值发生变化时,会执行里面的函数
// age变化不会执行watchEffect里面的函数
watchEffect(() => {
console.log("name:", name.value);
});
return {
name,
age,
changeName,
changeAge
}
}
}
</script>
2.watchEffect停止侦听
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const name = ref("zhangsan");
const age = ref(20);
// 用一个变量来接收watchEffect的返回值,返回值是一个函数
const stop = watchEffect(() => {
console.log("name:", name.value, "age:", age.value);
});
const changeAge = () => {
age.value++;
if (age.value > 25) {
// 执行watchEffect的返回值,就可以停止侦听
stop();
}
}
}
}
</script>
3.flush参数:需要等DOM元素挂载完,再去获取DOM元素的内容
<template>
<div>
<h2 ref="title">888888</h2>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const title = ref(null);
watchEffect(() => {
console.log(title.value);
}, {
flush: "post"
})
return {
title
}
}
}
</script>
三、watch
- watch需要指定侦听的数据源
- 只有当侦听的数据发生变化时才会执行回调
<template>
<div>
<h2 ref="title">{{info.name}}</h2>
<button @click="changeData">修改数据</button>
</div>
</template>
<script>
import { ref, reactive, watch } from 'vue';
export default {
setup() {
const info = reactive({name: "why", age: 18});
// 1.侦听watch时,传入一个getter函数
watch(() => info.name, (newValue, oldValue) => {
console.log("newValue:", newValue, "oldValue:", oldValue);
})
// 2.传入一个可响应式对象: reactive对象/ref对象
// 情况一: reactive 对象获取到的newValue和oldValue本身都是reactive对象
watch(info, (newValue, oldValue) => {
console.log("newValue:", newValue, "oldValue:", oldValue);
})
// 情况二: ref对象获取newValue和oldValue是value值的本身
const name = ref("why");
watch(name, (newValue, oldValue) => {
console.log("newValue:", newValue, "oldValue:", oldValue);
})
// 3.如果希望newValue和oldValue是一个普通的对象
watch(() => {
return {...info}
}, (newValue, oldValue) => {
console.log("newValue:", newValue, "oldValue:", oldValue);
})
const changeData = () => {
info.name = "kobe";
}
return {
changeData,
info
}
}
}
</script>