📚 이번 포스팅에서는 디렉티브에 대해서 다뤄보도록 하자.
'-v' 접두사가 있는 특수 속성
1) Directive의 속성 값은 단일 JavaScript 표현식이어야 함(v-for, v-on 제외)
2) 표현식 값이 변경될 때 DOM에 반응적으로 업데이트를 적용
<a v-bind:href="myUrl">URL</a>
이 예시의 href는 HTML a 요소의 href 속성 값을 myUrl 값에 바인딩하도록 하는 v-bind의 인자
<form v-on:submit.prevent="onSubmit">
<input type="submit">
</form>
이 예시의 .prevent는 발생한 이벤트에서 event.preventDefault()를 호출하도록 v-on에 지시하는 modifier
HTML 속성을 Vue 인스턴스의 데이터 변수와 연결
<template>
<img v-bind:src="imageSrc" :alt="imageAlt">
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const imageSrc = ref('https://example.com/image.jpg')
const imageAlt = ref('예시 이미지')
return {
imageSrc,
imageAlt
}
}
})
app.mount('#app')
</script>
조건에 따라 요소를 렌더링하거나 제거
<template>
<div>
<p v-if="type === 'A'">A 타입입니다</p>
<p v-else-if="type === 'B'">B 타입입니다</p>
<p v-else>기타 타입입니다</p>
</div>
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const type = ref('B')
return {
type
}
}
})
app.mount('#app')
</script>
조건에 따라 요소의 가시성을 토글
<template>
<p v-show="isVisible">이 텍스트는 토글됩니다</p>
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const isVisible = ref(true)
return {
isVisible
}
}
})
app.mount('#app')
</script>
배열이나 객체를 기반으로 요소를 반복 생성
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const items = ref([
{ id: 1, name: '사과' },
{ id: 2, name: '바나나' },
{ id: 3, name: '체리' }
])
return {
items
}
}
})
app.mount('#app')
</script>
DOM 이벤트를 리스닝하고 JavaScript 표현식이나 메서드를 실행
<template>
<button v-on:click="increment">클릭: {{ count }}</button>
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const count = ref(0)
const increment = () => {
count.value++
}
return {
count,
increment
}
}
})
app.mount('#app')
</script>
폼 입력 요소와 데이터를 양방향으로 바인딩
v-model은 단순 Text input 뿐만 아니라 Checkbox, Radio, Select 등 다양한 타입의 사용자 입력 방식과 함께 사용 가능
<template>
<input v-model="message" placeholder="메시지를 입력하세요">
<p>입력한 메시지: {{ message }}</p>
</template>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const message = ref('')
return {
message
}
}
})
app.mount('#app')
</script>