미리 계산된 속성을 사용하여 템플릿에서 표현식을 단순하게 하고 불필요한 반복 연산을 줄임
js
const todos = ref([
{ text: 'Vue 실습' },
{ text: '자격증 공부' },
{ text: 'TIL 작성' },
])
html
<h2>남은 할 일</h2>
<p>{{ todos.length > 0 ? '아직 남았다' : '퇴근!' }}</p>
템플릿이 복잡해지며 todos에 따라 계산을 수행하게 됨
만약 이 계산을 템플릿에 여러 번 사용하는 경우에는 반복이 발생
js
const { createApp, ref, computed } = Vue
const restOfTodos = computed(() => {
return todos.value.length > 0 ? '아직 남았다' : '퇴근!'
})
html
<h2>남은 할 일</h2>
<p>{{ restOfTodos }}</p>
js
const restOfTodos = computed() => {
return todos.value.length > 0 ? '아직 남았다' : '퇴근!'
})
js
const getRestOfTodos = function () {
return todos.value.length > 0 ? '아직 남았다' : '퇴근!'
}
html
<p>{{ getRestOfTodos() }}</p>
반면, method 호출은 다시 렌더링이 발생할 때마다 항상 함수를 실행
| computed | method |
|---|---|
| 의존된 데이터가 변경되면 자동으로 업데이트 | 호출해야만 실행됨 |
computed
method

js
const isSeen = ref(true)
html
<p v-if="isSeen">true일 때 보여요</p>
<p v-else>false일때 보여요</p>
<button @click="isSeen = !isSeen">토글</button>
js
const name = ref('Cathy')
html
<div v-if="name === 'Alice'">Alice입니다</div>
<div v-else-if="name === 'Bella'">Bella입니다</div>
<div v-else-if="name === 'Cathy'">Cathy입니다</div>
<div v-else>아무도 아닙니다.</div>
html
<template v-if="name === 'Cathy'">
<div>Cathy입니다</div>
<div>나이는 30살입니다</div>
</template>
<template> element"보이지 않는 wrapper 역할"
js
const isShow = ref(false)
html
<div v-show="isShow">v-show</div>
콘텐츠를 매우 자주 전환해야 하는 경우에는 v-show를, 실행중에 조건이 변경되지 않는 경우에는 v-if를 권장
alias in expression 형식의 특수 구문을 사용html
<div v-for="item in items">
{{ item.text }}
</div>
js
<div v-for="(item, index) in arr"></div>
<div v-for="value in object"></div>
<div v-for="(value, key) in object"></div>
<div v-for="(value, key, index) in object"></div>
js
const myArr = ref([
{ name: 'Alice', age: 20 },
{ name: 'Bella', age: 21 },
])
html
<div v-for="(item, index) in myArr">
{{ index }} / {{ item }}
</div>
js
const myInfo = ref([
{ name: 'Alice', age: 20, friends: ['Bella', 'Cathy', 'Dan'] },
{ name: 'Bella', age: 21, friends: ['Alice', 'Cathy'] },
])
html
<div v-for="(value, key, index) in myObj">
{{ index }} / {{ key }} / {{ value }}
</div>
html
<ul>
<template v-for="item in myArr">
<li>{{ item.name }}</li>
<li>{{ item.age }}</li>
<hr />
</template>
</ul>
js
const myInfo = ref([
{ name: 'Alice', age: 20, friends: ['Bella', 'Cathy', 'Dan'] },
{ name: 'Bella', age: 21, friends: ['Alice', 'Cathy'] },
])
html
<ul v-for="info in myInfo">
<li v-for="friend in info.friends">
{{ info.name }}의 친구들 - {{ friend }}
</li>
</ul>
js
const items = ref([
{ id: id++, name: 'Alice' },
{ id: id++, name: 'Bella' },
])
html
<div v-for="item in items" :key="item.id">
<p>{{ item }}</p>
</div>
Vue 내부 동작 관련 부분이기에 최대한 작성하려고 노력할 것
v-if에서의 조건은 v-for 범위의 변수에 접근할 수 없음
const todos = ref([
{ id: id++, name: '복습', isComplete: true },
{ id: id++, name: '예습', isComplete: false },
{ id: id++, name: '저녁식사', isComplete: true },
{ id: id++, name: '노래방', isComplete: false },
])
<ul>
<li v-for="todo in todos" v-if="todo.isComplete === false" :key="todo.id">{{ todo.name }}</li>
</ul>

js
const completeTodos = computed(() => {
return todos.value.filter((todo) =>
!todo.isComplete)
})
html
<ul>
<li v-for="todo in completeTodos" :key="todo.id">
{{ todo.name }}
</li>
</ul>
<template> 요소 활용html
<ul>
<template v-for="todo in todos" :key="todo.id">
<li v-if="!todo.isComplete">
{{ todo.name }}
</li>
</template>
</ul>
watch(source, (newValue, oldValue) => {
// do something
})
js
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log(`변화된 값: ${newValue} / 변하기 전 값: ${oldValue}`)
})
html
<button @click="count++">Add 1</button>
<p>Count: {{ count }}</p>
js
const message = ref('')
const messageLength = ref(0)
watch(message, (newValue) => {
messageLength.value = newValue.length
})
html
<input v-model="message" />
<p>Message length: {{ messageLength }}</p>
| Computed | watchers | |
|---|---|---|
| 공통점 | 데이터의 변화를 감지하고 처리 | 데이터의 변화를 감지하고 처리 |
| 동작 | 의존하는 데이터 속성의 계산된 값을 반환 | 특정 데이터 속성의 변화를 감시하고 작업을 수행 (side-effects) |
| 사용 목적 | 계산한 값을 캐싱하여 재사용 중복 계산 방지 | 데이터 변화에 따른 특정 작업을 수행 |
| 사용 예시 | 연산된 길이, 필터링된 목록 계상 등 | DOM 변경, 다른 비동기 작업 수행, 외부 API와 연동 등 |

Vue 컴포넌트 인스턴스가 초기 렌더링 및 DOM 요소 생성이 완료된 후 특정 로직을 수행하기
반응형 데이터의 변경으로 인해 컴포넌트의 DOM이 업데이트된 후 특정 로직을 수행하기
onBeforeMount: 컴포넌트가 마운트되기 전에 호출됩니다. DOM이 생성되기 전에 실행되어, 필요한 설정이나 초기화 작업을 수행할 수 있습니다.onMounted: 컴포넌트가 마운트된 후, 즉 DOM에 인스턴스가 부착된 직후에 호출됩니다. 이 시점에서 DOM 요소에 접근할 수 있으며, 외부 라이브러리를 연동하거나 추가적인 DOM 조작을 수행할 수 있습니다.onBeforeUpdate: 컴포넌트가 업데이트되기 전에 호출됩니다. 반응형 데이터가 변경되어 DOM이 업데이트되기 전에 필요한 로직을 수행할 수 있습니다.onUpdated: 컴포넌트의 데이터가 변경되어 DOM이 업데이트된 후 호출됩니다. 업데이트된 DOM에 대한 추가적인 처리를 수행할 수 있습니다.onBeforeUnmount: 컴포넌트가 언마운트되기 전에 호출됩니다. 이 훅에서는 타이머 제거, 이벤트 리스너 해제 등과 같은 정리 작업을 수행할 수 있습니다.onUnmounted: 컴포넌트가 완전히 언마운트된 후 호출됩니다. 모든 정리 작업이 완료되고, 컴포넌트가 DOM에서 제거된 후에 실행됩니다.<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
export default {
setup() {
const count = ref(0);
// onBeforeMount
onBeforeMount(() => {
console.log('Component is about to be mounted');
});
// onMounted
onMounted(() => {
console.log('Component has been mounted');
});
// onBeforeUpdate
onBeforeUpdate(() => {
console.log('Component will update');
});
// onUpdated
onUpdated(() => {
console.log('Component has updated');
});
// onBeforeUnmount
onBeforeUnmount(() => {
console.log('Component will unmount');
});
// onUnmounted
onUnmounted(() => {
console.log('Component has been unmounted');
});
function increment() {
count.value++;
}
return { count, increment };
}
};
</script>
<style>
/* CSS here */
</style>
computed의 반환 값은 변경하지 말것
computed 사용시 원본 배열 변경하지 말것
js
const numbers = ref([1, 2, 3, 4, 5])
const evenNumbers = computed(() => {
return numbers.value.filter((number) => number % 2 === 0)
})
html
<li v-for="num in evenNumbers">
{{ num }}
</li>
js
const numberSets = ref([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
])
const evenNumbers = function (numbers) {
return numbers.filter((number) => number % 2 === 0)
}
html
<ul v-for="numbers in numberSets">
<li v-for="num in evenNumbers(number)">
{{ num }}
</li>
</ul>
직접 고유한 겂을 만들어내는 메서드를 만들거나 외부 라이브러리 등을 활용하는 등 식별자 역할을 할 수 있는 값을 만들어 사용