🧾 Vue Script Syntax란?

정의

Vue Script Syntax는 Vue 컴포넌트의 <script> 영역에서 상태와 동작을 작성하는 문법이다.

Composition API를 기준으로 ref, reactive, computed, watch 같은 기능을 자주 사용한다.

🧩 ref

  • 기본형 값이나 단일 상태를 반응형으로 만들 때 사용한다.
  • 값은 .value로 접근한다.
<script setup>
import { ref } from "vue";

const message = ref("안녕 Vue!");
message.value = "변경된 텍스트";
</script>

🧱 reactive

  • 객체나 배열처럼 여러 속성을 가진 상태를 반응형으로 만들 때 사용한다.
  • 객체 자체를 Proxy로 감싼다.
<script setup>
import { reactive } from "vue";

const state = reactive({
  count: 0,
});
</script>

🔍 computed

  • 다른 반응형 값에 의존하는 계산된 값을 만들 때 사용한다.
  • 캐시되기 때문에 불필요한 계산을 줄일 수 있다.
<script setup>
import { reactive, computed } from "vue";

const author = reactive({
  name: "John Doe",
  books: ["Vue 2", "Vue 3", "Vue 4"],
});

const publishedBooksMessage = computed(() => {
  return author.books.length > 0 ? "Yes" : "No";
});
</script>

👀 watch

  • 특정 반응형 값의 변화를 감시한다.
  • 값이 바뀔 때마다 콜백이 실행된다.
<script setup>
import { ref, watch } from "vue";

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`newValue: ${newValue}, oldValue: ${oldValue}`);
});
</script>

🕵️ watchEffect

  • 내부에서 사용하는 반응형 값을 자동으로 추적한다.
  • 여러 의존성을 한 번에 감시할 때 편하다.
<script setup>
import { ref, watchEffect } from "vue";

const count = ref(0);

watchEffect(() => {
  console.log("count:", count.value);
});
</script>

⏭️ nextTick

  • DOM 업데이트가 반영된 다음 시점까지 기다릴 때 사용한다.
<script setup>
import { nextTick, ref } from "vue";

const count = ref(0);

async function increment() {
  count.value++;
  await nextTick();
}
</script>

🧪 활용 예시

<script setup>
import { ref, computed, watch } from "vue";

const title = ref("기초");
const author = ref("");

const bookInfo = computed(() => `${title.value} - ${author.value}`);

watch(bookInfo, (newValue) => {
  console.log("bookInfo changed:", newValue);
});
</script>

📌 정리

  • Vue Script Syntax는 Composition API 상태 관리의 기본이다.
  • ref, reactive, computed, watch, watchEffect, nextTick를 먼저 익히면 된다.
  • Vue-ComponentVue-Template Syntax와 함께 보면 구조가 잘 보인다.

연결문서

댓글남기기