在 Vue3 中,可以使用watch函数来监听属性的变化。

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newVal, oldVal) => {
      console.log(`count changed from ${oldVal} to ${newVal}`);
    });

    return { count };
  }
}

在上面的例子中,我们使用ref函数创建了一个响应式的属性count,然后使用watch函数来监听count的变化。当count发生变化时,回调函数会被触发,将新值和旧值作为参数传入。

除了监听单个属性的变化,还可以使用watch函数来监听多个属性的变化。

import { ref, watch } from 'vue';

export default {
  setup() {
    const firstName = ref('');
    const lastName = ref('');

    watch([firstName, lastName], ([newFirstName, newLastName], [oldFirstName, oldLastName]) => {
      console.log(`name changed from ${oldFirstName} ${oldLastName} to ${newFirstName} ${newLastName}`);
    });

    return { firstName, lastName };
  }
}

在上面的例子中,我们使用watch函数同时监听firstNamelastName的变化。当任何一个属性发生变化时,回调函数会被触发,将新值和旧值作为参数传入。

Vue3 属性变化监听:watch 函数详解 - 详细教程

原文地址: https://www.cveoy.top/t/topic/p14O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录