vue3计算属性与侦听器

161 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第14天,点击查看活动详情

之前我们在vue2的时候介绍过计算属性和侦听器,其实在vue3中,计算属性和侦听器的功能和在vue2中的差不多,只是用法稍微不同。

计算属性

我们一般使用计算属性来描述依赖响应式状态的复杂逻辑。

计算属性的用法

在vue3中计算属性的用法和在vue2中的不一样。

<div>姓名:{{fullname}}</div>

<script setup>
import { reactive, computed } from 'vue';
const person = reactive({
  firstName: '安妮',
  lastName: '海瑟薇'
});
const fullname = computed(() => {
  return `${person.firstName}·${person.lastName}`;
});
console.log('fullname', fullname);
</script>

效果如下:

image.png 从上述效果图中我们可以看出,计算属性返回的变量相当于是一个使用ref定义的响应式变量。需要通过.value来获取值。

计算属性的完整用法

const fullname = computed({
  get() {
    return `${person.firstName}·${person.lastName}`;
  },
  // setter
  set(newValue) {
    // 注意:我们这里使用的是解构赋值语法
    [person.firstName, person.lastName] = newValue.split(' ')
  }
});

计算属性除了定义可读,它也可以设置可写(不建议)。

计算属性的使用场景

我们一般使用计算属性都是对复杂的可读的属性想要响应式,只采用可读。

侦听器

和vue2一样,我们可以使用 watch 函数在每次响应式状态发生变化时触发回调函数。 由于vue3中数据分为基本类型和复杂类型的响应式数据,因此在使用watch监听的时候也分为以下几种。

watch监听ref

import { ref, watch } from 'vue';
const a = ref(0);
const b = ref(0);

// 监听单个 ref
watch(a, (newVal) => {
  console.log(`a is ${newVal}`)
});

// 使用getter 函数监听
watch(
  () => a.value + b.value,
  (sum) => {
    console.log(`sum of a + b is: ${sum}`)
  }
);

// 监听多个来源组成的数组
watch([a, () => b.value], ([newA, newy]) => {
  console.log(`a is ${newA} and b is ${newy}`)
});

watch监听props属性

import { ref, reactive, computed, defineProps, watch } from 'vue';
const props = defineProps({
  name: {
    type: String,
    default: ''
  }
});
watch(
  () => props.name,
  (newVal) => {
    console.log(`name is: ${newVal}`)
})

watch监听对象

watch监听对象的属性的时候需要用一个返回该属性的 getter 函数:

import { ref, reactive, computed, defineProps, watch } from 'vue';
const person = reactive({
  name: ''
});
watch(
  () => person.name,
  (newVal) => {
    console.log(`name is: ${newVal}`)
})

如果用下列watch监听对象,必须是直接给person重新赋值才能被监听

import { ref, reactive, computed, defineProps, watch } from 'vue';
const person = reactive({
  name: '',
  age: 18
});
watch(
  () => person,
  (newVal) => {
    console.log(`person is: ${newVal}`)
})

深度监听

如果想监听上述person对象,只要里面任意属性改变都能监听到的话,就需要使用深度监听。

import { ref, reactive, computed, defineProps, watch } from 'vue';
const person = reactive({
  name: '',
  age: 18
});
watch(
  () => person,
  (newVal) => {
    console.log(`person is: ${newVal}`)
  },{
    deep: true
  })

即时监听

watch 默认是懒执行的:仅当数据源变化时,才会执行回调。但在某些场景中,我们希望在创建侦听器时,立即执行一遍回调。那么就需要使用immediate: true来配置

import { ref, reactive, computed, defineProps, watch } from 'vue';
const person = reactive({
  name: '',
  age: 18
});
watch(
  () => person,
  (newVal) => {
    console.log(`person is: ${newVal}`)
  },{
    deep: true
  },{ 
    immediate: true 
  })