vue3 computed与watch属性

学习随笔(Vue3)

computed属性

  1. 选项式写法 支持一个对象传入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 = '圆子-同学'
}
  1. 函数式写法 只能支持一个getter函数,不允许修改值的
let name = computed(() => {
  firstName.value + '-' + lastName.value;
})
  1. 基础的操作案例,比如:计算总价,总数,或者进行搜索操作

watch属性

  1. 普通用法(ref),例:
import {ref,watch} from "vue";

const name = ref<string>('圆子同学');

// 这是最简单的用法 第一个值为监控的值,第二个为操作方法,与vue2类似
watch(name,(newVal,oldVal) => {
  console.log(newVal,oldVal)
})

但是这样的watch属性只能监听浅层数据,无法监测深层数据,那么我们就要加入deep:trueoption属性来实现深层监听,比如:

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,
})
  1. 深层监听(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)
})

接下来,讲讲watchoption配置属性:

  • deep:false 深度监听(默认false)
  • immediate:false 立即执行一次(默认false)
  • flush:'pre' 调用方式(默认"pre",可选值为:"post","sync","pre"),"pre":组件更新之前调用,"sync":同步执行,"post":组件更新之后调用
  1. 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;
posted @ 2023-09-18 15:27  圆子同学  阅读(54)  评论(0)    收藏  举报