Vue

[Vue] Watch 속성

yangjoy 2021. 9. 12. 20:53

1 Watch 속성


computed속성 vs watch 속성

watch를 사용했을 때보다 computed를 사용했을 때 코드가 더 짧다.

최대한 computed 속성을 우선적으로 사용하고

불가피할때 watch를 사용하는 것이 좋다.

 

 

watch 속성

    <div id="app">
        {{message}}<br>
        <button @click="changeMessage">Click</button><br>
        {{updated}}

    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                message: '헬로우',
                updated: '아니오'
            },
            methods: {
                changeMessage(){
                    this.message = '바이바이';
                }
            },
            computed:{   
            },
            watch:{
                message(newVal, oldVal){
                    console.log(newVal, oldVal);
                    this.updated = '네';
                }
            }
        })
    </script>

결과값 :

클릭 이벤트 후 :