본문 바로가기
study/Vue.js

Vue.js watch computed : 캐시 메모리저장 여부 / 코드 복잡도 차이

by 고기만두(개발자) 2022. 6. 7. 19:25
728x90
반응형

1. Watch

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script>
        window.onload = function(){
            var vm1 = new Vue({
                el : '#test1',
                data : {
                    a1 : '',
                    a2 : '',
                    a3 : ''
                },
                watch : {
                    //변수 a1을 감시하는 watch
                    a1 : function(newVal, oldVal){
                        console.log('a1의 새로운 값: ' + newVal + ', 이전 값: '+ oldVal)
                        this.a3 = 'a1 : ' + newVal
                    },
                    //변수 a2을 감시하는 watch
                    a2 : function(newVal, oldVal){
                        console.log('a2의 새로운 값: ' + newVal + ', 이전 값: '+ oldVal)
                        this.a3 = 'a2 : ' + newVal
                    }
                }
            })
        }
    </script>
</head>
<body>
    <div id = "test1">
        input1 : <input type = 'text' v-model = 'a1'/><br/>
        input2 : <input type = 'text' v-model = 'a2'/><br/>
        <h3>{{a1}}</h3>
        <h3>{{a2}}</h3>
        <h3>{{a3}}</h3>
    </div>
</body>
</html>

vue.js watch

값이 바뀔 때마다 콘솔에 실시간으로 변경이 인식되는 것이 watch의 특징이다.

그리고 a3이라는 변수를 지정해서 그 변경값을 실시간으로 찍을 수 있도록 했다.


2. Computed 

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script>
        window.onload = function(){
            var vm1 = new Vue({
                el: '#test1',
                data : {
                    a1 : 100,
                    a2 : 200
                },
                methods : {     //반환하는 값이 같더라도, 함수는 계속 호출되어야 함
                    test_method : function(){
                        console.log('test method')
                        return this.a1 + this.a2
                    },
                    setValue : function(){
                        this.a1 = 1000
                        this.a2 = 2000
                    },
                    getRandomMethod : function(){
                        return Math.random()
                    }
                },
                computed : {    //반환값이 변하지 않는다면, 이전 반환값을 메모리에 기억해놨다가 메모리에서 그 값을 그대로 출력 - 호출되는 횟수만큼 콘솔로그 출력
                    test_computed : function(){
                        console.log('test computed')
                        return this.a1 + this.a2
                    },
                    getRandomComputed : function(){
                        return Math.random()
                    }   //computed는 3번을 불러와도 랜덤으로 한번 불러온 값 저장했다가 갖다 씀 : 그래서 똑같음
                }
            })
        }
    </script>
</head>
<body>
    <div id = 'test1'>
        <h3>a1 : {{a1}}</h3>
        <h3>a2 : {{a2}}</h3>
        <h3>a1+a2 : {{a1 + a2}}</h3>
        <h3>test method : {{test_method()}}</h3>
        <h3>test method : {{test_method()}}</h3>
        <h3>test method : {{test_method()}}</h3>
        <h3>test computed : {{test_computed}}</h3>
        <h3>test computed : {{test_computed}}</h3>
        <h3>test computed : {{test_computed}}</h3>

        <button type='button' v-on:click='setValue'>값 변경</button>

        <h3>get random method : {{getRandomMethod()}}</h3>
        <h3>get random method : {{getRandomMethod()}}</h3>
        <h3>get random method : {{getRandomMethod()}}</h3>

        <h3>get random computed : {{getRandomComputed}}</h3>
        <h3>get random computed : {{getRandomComputed}}</h3>
        <h3>get random computed : {{getRandomComputed}}</h3>
    </div>
</body>
</html>

3번을 연달아 부를 때

method로 계산하면, 세 번을 모두 불러온다.

 

그러나, 반환되는 값이 같을 경우에는 computed로 불러오면,

메모리에 저장해놨다가 한 번만 호출하고 그 값을 그대로 꺼내먹는다.

값 변경 버튼을 통해 setValue를 다시해도 마찬가지이다.

랜덤값을 호출할때도 역시나 그렇다.

 

setvalue
vue.js 결과


3. 그래서 둘의 차이가 뭐냐고? - 실시간성

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script>
        window.onload = function(){
            var vm1 = new Vue({
                el : '#test1',
                data : {
                    data1 : 'aaa',
                    data2 : 'bbb',
                    result1 : ''
                },
                watch : {
                    data1 : function(){
                        this.result1 = 'data1 : ' + this.data1 + ',data2 : ' + this.data2
                        //어 그런데 data2는 계속 실시간으로 변경이 안되는 이유 무엇? : data2에 watch를 셋팅하지 않아서
                    },
                    data2 : function(){
                        this.result1 = 'data1 : ' + this.data1 + ',data2 : ' + this.data2
                    }
                },
                computed : {    //모든 변수를 감시 가능 - 반복된 코드를 하나로 통합가능
                    result2 : function(){
                        return 'data1 : ' + this.data1 + ', data2 : ' + this.data2
                    }
                }
            })
        }
    </script>
</head>
<body>
    <div id = 'test1'>
        <input type = 'text' v-model = 'data1'/><br/>
        <input type = 'text' v-model = 'data2'/><br/>
        <h3>result1</h3>
        <div>{{result1}}</div>
        <h3>result2</h3>
        <div>{{result2}}</div>
    </div>
</body>
</html>

computed의 장점 하나 더.

모든 변수를 감시할 수 있다.

watch는 일일이 각 변수에 대한 result 값을 찍어낼 수 있는 함수를 만들어야 한다.

그런데 computed는 그럴 필요가 없이 그냥 묶어서 한줄컷 가능하므로, 반복되는 코드를 하나로 통합시킬 수 있다는 장점.

result1과 result2의 결과는 같지만, 코드 복잡도의 차이 정도/

vue.js watch computed

728x90
반응형

댓글