본문 바로가기

Frontend/Vue3

[Vue3] watch

728x90
반응형

watch() 함수는 반응형 데이터를 감시하고, 감시하는 데이터가 변경되면 콜백 함수를 호출한다.

watch 구조

watch(variable, (newValue, oldValue) => {
  // do something
}

- variable: 감시하는 변수

watch 예시

감시하는 변수에 변화가 생겼을 때 기본 동작 확인하기

<body>
    <div id="app">
      <button @click="count++">Add 1</button>
      <p>Count: {{ count }}</p>
    </div>

    <script>
      const { createApp, ref, watch } = Vue;

      const app = createApp({
        setup() {
          const count = ref(0);

          const countWatch = watch(count, (newValue, oldValue) => {
            console.log(`newValue: ${newValue}, oldValue: ${oldValue}`);
          });

          return {
            count,
          };
        },
      });

      app.mount("#app");
    </script>
  </body>

 

감시하는 변수에 변화가 생겼을 때 연관 데이터 업데이트하기

<body>
    <div id="app">
      <input v-model="message" />
      <p>Message length: {{ messageLength }}</p>
    </div>

    <script>
      const { createApp, ref, watch } = Vue;

      const app = createApp({
        setup() {
          const message = ref("");
          const messageLength = ref(0);

          const messageWatch = watch(message, (newValue, oldValue) => {
            messageLength.value = newValue.length;
          });

          return {
            message,
            messageLength,
          };
        },
      });

      app.mount("#app");
    </script>
  </body>

728x90
반응형

'Frontend > Vue3' 카테고리의 다른 글

[Vue3] 컴포넌트 간 통신 (props, emit)  (0) 2024.05.07
[Vue3] Lifecycle Hooks  (0) 2024.05.06
[Vue3] 리스트 렌더링 (v-for)  (0) 2024.05.06
[Vue3] 조건부 렌더링 (v-if, v-show)  (0) 2024.05.06
[Vue3] Computed Property  (0) 2024.05.06