vue3 computed与watch属性
学习随笔(Vue3)
- 该随笔是根据b站小满zs的Vue3 + vite + Ts + pinia + 实战 + 源码 +electron的视频学习写的,Vue3 + vite + Ts + pinia + 实战 + 源码 +electron
computed属性
- 选项式写法 支持一个对象传入get函数以及set函数自定义操作
import {ref,computed} from 'vue';
let firstName = ref('圆');
let lastName = ref('子');
let name = computed<string>({
get(){
return firstName.value + lastName.value;
},
set(newValue){
[firstName.value, lastName.value] = newValue.split('-');
}
})
const changeName = ()=> {
name.value = '圆子-同学'
}
- 函数式写法 只能支持一个getter函数,不允许修改值的
let name = computed(() => {
firstName.value + '-' + lastName.value;
})
- 基础的操作案例,比如:计算总价,总数,或者进行搜索操作
watch属性
- 普通用法(ref),例:
import {ref,watch} from "vue";
const name = ref<string>('圆子同学');
// 这是最简单的用法 第一个值为监控的值,第二个为操作方法,与vue2类似
watch(name,(newVal,oldVal) => {
console.log(newVal,oldVal)
})
但是这样的watch属性只能监听浅层数据,无法监测深层数据,那么我们就要加入deep:true的option属性来实现深层监听,比如:
import {ref,watch} from "vue";
const name = ref({
foot: {
bar: {
name: "圆子同学"
}
}
});
// 加入deep:true,可以监听深层结构的数据,但是newVal与oldVal的值一样,这不符合我们的要求
watch(name,(newVal,oldVal) => {
console.log(newVal,oldVal)
},{
deep: true,
})
- 深层监听(reactive),由于使用
ref响应数据进行深层监听的时候会发现前后值一致,所以使用reactive进行深层监听,例:
import {reactive,watch} from "vue";
const name = reactive({
foot: {
bar: {
name: "圆子同学"
}
}
});
// 使用reactive属性进行监听时,无需使用deep:true属性,因为reactive自带deep
watch(name,(newVal,oldVal) => {
console.log(newVal,oldVal)
})
// 如果要监听这个属性的单一值,那么我们就要给他变成一个函数,例:
watch(() => name.foot.bar.name,(newVal,oldVal) => {
console.log(newVal,oldVal)
})
接下来,讲讲watch的option配置属性:
- deep:false 深度监听(默认false)
- immediate:false 立即执行一次(默认false)
- flush:'pre' 调用方式(默认"pre",可选值为:"post","sync","pre"),"pre":组件更新之前调用,"sync":同步执行,"post":组件更新之后调用
- watchEffect 的作用
当依赖项发生改变的时候,重新执行该函数,其实就是个监听函数
import {watchEffect, ref} from 'vue';
let message = ref<string>('黑丝');
let message2 = ref<string>('黑丝美女');
// 这是最常用的方法,开始就会被调用
watchEffect(() => {
console.log('message====>', message);
console.log('message2====>', message2);
})
watchEffect((oninvalidate) => {
console.log('message====>', message);
console.log('message2====>', message2);
// 按照正常的代码顺序,应当是先显示message后显示下方代码,但实际上是先显示下方代码,再显示message
// 这就是oninvalidate回调函数的作用,先被调用,可以用来清除副作用
oninvalidate(() => {
console.log("我被调用了");
})
})
当然这个函数也是可以被停止的,例如:
import {watchEffect, ref} from 'vue';
let message = ref<string>('黑丝');
let message2 = ref<string>('黑丝美女');
// 停止调用就是这个函数的回调函数
const stop = watchEffect(() => {
console.log('message====>', message);
console.log('message2====>', message2);
});
const stopWatch = () => stop;
本文来自博客园,作者:圆子同学,转载请注明原文链接:https://www.cnblogs.com/yuanZi666/p/17712079.html

浙公网安备 33010602011771号