Vue3的watchEffect函数

使用watch函数监听时,需要指明要监听的属性及其对应的回调。
使用watchEffect函数监听时,不需要指明要监听的属性,在监听回调中用到了哪个属性,就会监听哪个属性。

看具体的例子吧 。

  • main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  • App.vue
<template>
  <Demo/>
template>

<script>
import Demo from './components/Demo.vue'

export default {
  name: 'App',
  components: {
    Demo
  }
}
script>
  • Demo.vue
<template>
  <h2>sum的当前值为:{{sum}}h2>
  <button @click="sum++">修改sumbutton>
  <hr>
  <h2>msg的当前值为:{{msg}}h2>
  <button @click="msg+='!'">修改msgbutton>
  <hr>
  <h2>姓名:{{person.name}}h2>
  <h2>年龄:{{person.age}}h2>
  <h2>薪酬:{{person.job.salary}}Kh2>
  <button @click="person.name+='~'">修改姓名button> 
  <button @click="person.age++">增长年龄button> 
  <button @click="person.job.salary++">涨薪button>
template>

<script>
import {ref, reactive, watch, watchEffect} from "vue";
export default {
  name: 'Demo',
  setup(){
    let sum = ref(0);
    let msg = ref("你好");
    let person = reactive({
      name:"张三",
      age:18,
      job:{
        salary:30
      }
    })

    watch(sum,(newValue,oldValue) => {
      console.log("sum变了");
    })
    watch(msg,(newValue,oldValue) => {
      console.log("msg变了");
    })
    watch(person,(newValue,oldValue) => {
      console.log("person变了");
    })

    watchEffect(() => {
      let x1 = sum.value;
      let x2 = person.job.salary;
      console.log("watchEffect指定的回调执行了");
    })

    return {
      sum,
      msg,
      person
    }
  }
}
script>
  • 启动应用,测试效果
    Vue3的watchEffect函数_第1张图片
    watchEffect的监听回调中用到了sumperson.job.salary,所以当sum或者person.job.salary发生变化时,就会触发watchEffect的监听回调,从而在控制台打印出"watchEffect指定的回调执行了"。

你可能感兴趣的:(Vue3,watchEffect,监听属性,监听回调)