Vue.js

[Vue.js] Watch 속성

솔솔 2021. 9. 19. 14:21
반응형
  • 대부분의 경우 computed 속성이 더 적합하지만 간혹 감시자가 필요한 경우 watch 속성이 필요
  • 변경되는 값을 캐치하고 싶을 때 watch 사용

button 클릭시 changeMessage()가 호출되며 메시지가 '안녕하세요' -> 'Hello'로 바뀐다. 그 message가 바뀌는 시점에 watch가 호출되고 파라미터는 새로운 값, 예전 값이 넘어오게 된다.

(여기서 새로운 값 : Hello, 예전 값 : 안녕하세요)

<div id="app">
        {{ message }} <br>
        <button @click="changeMessage">Button Click</button> <br>
        {{ updated }}
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
    <script>
    	new Vue({
        	el: '#app',
          data: {
            message: '안녕하세요',
            updated: '아니요'
          },
          methods: {
            changeMessage() {
            	this.message = 'Hello';
            }
          },
          watch: {
            message(newVal, oldVal) {
              console.log(newVal, " | ", oldVal);
              this.updated = '예'
            }
          }
        })
    </script>
반응형