Vue


监听属性 watch

watch 监听基础类型:

<template>
  <button @click="change">更改</button>
</template>
<script setup>
import { ref, watch } from "vue";

const num = ref(9);
function change() {
  num.value = 10;
}
watch(num, (newVal, oldVal) => {
  console.log("old", oldVal);
  console.log("new", newVal);
  console.log(num.value);
});
</script>


watch 监听对象:要使用deep属性深度监听

<template>
  <button @click="change">更改</button>
</template>
<script setup>
import { ref, watch } from "vue";

const name = ref({
  firstName: "Andy",
  lastName: "Zhou",
});
function change() {
  name.value.lastName = "lalala";
}
watch(
  name,
  (oldVal, newVal) => {
    console.log(oldVal);
    console.log(newVal);
    console.log(name.value);
  },
  {
    deep: true, //deep 深度监视对象内的内容
  }
);
</script>


watch 监听多个属性

<template>
  <button @click="change">更改</button>
</template>
<script setup>
import { ref, watch } from "vue";

const num1 = ref(9);
const num2 = ref(90);
function change() {
  num1.value = 10;
  // num2.value = 100;
}
watch([num1, num2], (newVal, oldVal) => {
  console.log("old", oldVal);
  console.log("new", newVal);
  console.log(num1.value);
});
</script>


watch 监听立即执行:使用 immediate

<template>
  <button @click="change">更改</button>
</template>
<script setup>
import { ref, watch } from "vue";
const num1 = ref(9);
function change() {
  num1.value = 10;
}
watch(
  num1,
  (newVal, oldVal) => {
    console.log("old", oldVal);
    console.log("new", newVal);
    console.log(num1.value);
  },
  {
    immediate: true,
  }
);
</script>

页面列表

ITEM_HTML