• 声明属性
  • 通过vue按需引入watch
  • 对指定声明的属性实行监听
<template>
  <el-button type="primary" @click="handleChangeData">修改数据触发watch监听</el-button>
  <div class="count">{{sNum}}</div>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, watchEffect, watch } from "vue";

export default defineComponent({
  name: "Box",
  setup() {
    let state = reactive({
      sNum: 1,
      sObj: {
        account: "zhangsan",
        password: 111111,
      },
      fontColor: "black",
    });

    let rNum = ref(2);
    let rObj = ref({account: "lisi", password: 222222});

    let handleChangeData = ()=>{
      // 修改reactive声明的属性
      state.sNum = 2;
      state.sObj = {
        account: "wangwu",
        password: 333333,
      };
      // 修改ref声明的属性
      rNum.value = 3;
      rObj.value = {
        account: "laoliu",
        password: 444444,
      };
    }
    
    /**
     * 1、通过reactive声明的属性
     */
    // 1.1、即刻监听 immediate
    watch(() => state.sNum, (value) => {
      console.log(value, "sNum即刻监听");
    }, {immediate: true});
    // 1.2、普通监听
    watch(() => state.sNum, (value) => {
      console.log(value, "sNum改变了");
    });
    // 1.3、监听多个数据
    watch([() => state.sNum, () => state.sObj], (value) => {
      console.log(value, "多个");  // [1, Proxy]  Proxy.的方式即可拿到改变后的数据 
    });
    // 1.4、深度监听
    watch(() => state.sObj, (value) => {
      console.log(value, "sObj改变了");
    }, {deep: true});
    
    /**
     * 2、通过ref声明的属性
     */
     // 2.1、即刻监听 immediate
    watch(rNum, (value) => {
      console.log(value, "rNum即刻监听");
    }, {immediate: true});
    // 2.2、普通监听
    watch(rNum, (value) => {
      console.log(value, "rNum改变了");
    });
    // 2.3、监听多个数据
    watch([rNum, rObj], (value) => {
      console.log(value, "多个");  // [3, Proxy]  "Proxy."的方式即可拿到改变后的数据
    });
    // 2.4、深度监听
    watch(rObj, (value) => {
      console.log(value, "rObj改变了");
    }, {deep: true});
    
    /**
     * 3、watchEffect 
     * 立即执行传入的一个函数,并响应式追踪其依赖,并在其依赖变更时重新运行该函数
     */
    watchEffect(() => {
      if (state.sNum % 2) {
        state.fontColor = "deeppink";
      } else {
        state.fontColor = "blue";
      }
    });
    return {
      ...toRefs(state),
      rNum,
      rObj,
      handleChangeData,
    };
  },
});
</script>

<style lang="scss" scope>
.count {
  color: v-bind(fontColor);
  font-weight: bold;
  font-size: 20px;
}
</style>
Logo

前往低代码交流专区

更多推荐