[Vue.js] tutorial - 10. Watchers

2024. 8. 3.·🎨 프론트엔드 공부/Vue & Nuxt

📍watch

- watchers를 사용하면 사이드 이펙트를 반응적으로 수행할 수 있다

- 예) 특정 값이 바뀌면 콘솔에 숫자 출력하기

import { ref, watch } from 'vue'

const count = ref(0)

watch(count, (newCount) => {
  // yes, console.log() is a side effect
  console.log(`new count is: ${newCount}`)
})

- 위 예시에서 count의 값이 바뀌면 콜백 함수가 실행된다

- ref 말고도 다른 타입의 데이터를 watch가 감지하게 할 수 있다

- 예시

<script setup>
import { ref, watch } from 'vue'

const todoId = ref(1)
const todoData = ref(null)

async function fetchData() {
  todoData.value = null
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${todoId.value}`
  )
  todoData.value = await res.json()
}

fetchData() // 최초 1번은 실행됨(안그러면 todoData가 null)

watch(todoId, fetchData) // todoId가 바뀔 때마다 fetchData 실행
</script>

<template>
  <p>Todo id: {{ todoId }}</p>
  <button @click="todoId++" :disabled="!todoData">Fetch next todo</button>
  <p v-if="!todoData">Loading...</p>
  <pre v-else>{{ todoData }}</pre>
</template>
'🎨 프론트엔드 공부/Vue & Nuxt' 카테고리의 다른 글
  • [Vue.js] tutorial - 12. Props
  • [Vue.js] tutorial - 11. Components
  • [Vue.js] tutorial - 9. Lifecycle and Template Refs
  • [Vue.js] tutorial - 8. Computed Property
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (510)
      • 🎨 프론트엔드 공부 (247)
        • JS & TS (86)
        • HTML & CSS (22)
        • React & Next (49)
        • Vue & Nuxt (22)
        • 기타 (68)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (6)
        • Work (0)
        • Toy (6)
      • ⚙️ 개발 팁 & 노하우 (21)
        • 프론트엔드 (6)
        • 기타 (15)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
[Vue.js] tutorial - 10. Watchers
상단으로

티스토리툴바