[vue] The difference between computed and watch in vue

Many people are confused about computed and watch. In fact, the uses of the two are completely different. There is no need to explain it in a long way.

computed is used to calculate and generate new data. This data is cached.

watch is to monitor existing data

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

[Note] Using computed can also optimize the project because computed is cached. In the above example, as long as the values ​​of countA and countB do not change, the value of sum will not be recalculated every time.

Guess you like

Origin blog.csdn.net/wuguidian1114/article/details/123395414