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

2022-02-24  本文已影响0人  张中华

区别:

示例:



示例代码:

<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>

上一篇 下一篇

猜你喜欢

热点阅读