[vue] vueでのcomputedとwatchの違い

多くの人が computed と watch を混同していますが、実際、この 2 つの用途はまったく異なるものであり、長々と説明する必要はありません。

computed は、新しいデータを計算して生成するために使用され、このデータはキャッシュされます。

watch は既存のデータを監視することです

<template>
  <div> 总共 {
   
   {sum}}</div>
</template>

<script>
export default {
    data() {
        return {
            name:'zhangsan',
            countA:2,
            countB:8
        }
    },
    watch: {
        name(newValue, oldValue) {
            console.log('watch name', newValue, oldValue)
        }
    },
    computed: {
        sum() {
            // 有缓存
            return this.countA + this.countB
        }
    },
    methods: {
        getSum() {
            // 无缓存
            return this.countA + this.countB
        }
    },
}
</script>

[注意] computedを使用するとcomputedがキャッシュされるためプロジェクトを最適化することもできます 上記例ではcountAとcountBの値が変わらない限りsumの値が毎回再計算されることはありません。

おすすめ

転載: blog.csdn.net/wuguidian1114/article/details/123395414