美文网首页
vue3较vue2的特别之处 - watch/watchEffe

vue3较vue2的特别之处 - watch/watchEffe

作者: 张中华 | 来源:发表于2022-02-24 11:24 被阅读0次

区别:

  • watch可以查看旧值, watchEffect不可以。
  • watch只有属性改变才执行, watchEffect初始执行一次,属性改变再执行。
  • watch要指定属性, watchEffect不需要。
  • watch不可以停止监听, watchEffect可以。
  • watch多次触发多次执行(不能节流), watchEffect可以。

示例:



示例代码:

<template>
  <div>count: {{ count }}</div>
  <button @click="clickPlus">加号123</button>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onBeforeMount,
  onUpdated,
  ref,
  watch,
  watchEffect,
} from "vue";

export default defineComponent({
  setup() {
    console.log('初始化开始');
    
    const count = ref(0);
    const clickPlus = () => {
      count.value++;
    };

    watch(
      () => count.value,
      (newValue, oldValue) => {
        console.log("watch: newValue: " + newValue + ', oldValue: ' + oldValue);
      }
    );

// sotp可以用来停止监听
    const stop = watchEffect(() => {
      console.log("watchEffect: " + count.value);
    });

    onUpdated(() => { console.log('updated'); });

    return {
      count,
      clickPlus,
    };
  },

  data() {return {}},

  methods: {},
});
</script>

<style scoped></style>

相关文章

网友评论

      本文标题:vue3较vue2的特别之处 - watch/watchEffe

      本文链接:https://www.haomeiwen.com/subject/ibbolrtx.html