11. event modifiers
주제
이 강의의 마지막 부분에서는 Vue에서 이벤트를 다룰 때 고려해야 할 한 가지 중요한 사항, 바로 '이벤트 수정자(Event Modifiers)'에 대해 설명합니다. 일반적으로 대부분의 애플리케이션에서는 기본 브라우저 동작이 애플리케이션에 영향을 미치지 않도록 event.preventDefault 메소드를 호출합니다. 하지만 이 방법은 반복적이고 코드를 복잡하게 만듭니다.
Vue는 이를 간소화할 수 있는 '이벤트 수정자' 기능을 제공합니다. 이벤트 수정자는 이벤트 처리 방식을 변경하는 데 사용됩니다. 강의에서는 Vue 공식 문서 링크를 제공하여 이벤트 수정자에 대해 자세히 알아볼 수 있습니다. 이벤트 수정자는 메소드가 DOM 이벤트 세부 사항을 다루는 대신 순수하게 데이터 로직에만 집중할 수 있도록 도와줍니다.
예를 들어, 템플릿 내의 입력 이벤트에 이벤트 수정자를 적용할 수 있습니다. 이벤트 수정자는 이벤트 이름 뒤에 점(.)을 추가하고 사용하려는 수정자를 지정함으로써 사용할 수 있습니다. 예를 들어, 기본 이벤트 동작을 중지하고 싶을 때 Vue의 'prevent' 이벤트 수정자를 사용할 수 있습니다. 이를 추가하면 함수 내에서 preventDefault 메소드를 호출하는 것과 동일한 효과를 냅니다.
이렇게 이벤트 수정자를 사용하면 코드를 훨씬 깔끔하고 간결하게 만들 수 있습니다. 페이지를 새로고침하고 입력 필드에 타이핑하면 여전히 모든 것이 정상적으로 작동하며, 콘솔은 변경 사항마다 메시지를 로깅합니다. 이벤트 수정자를 사용하면 Vue에서 이벤트를 처리하는 것이 간단해지며, 보통 작성해야 할 코드의 양을 줄일 수 있어 코드를 정돈되고 조직적으로 유지할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="app" v-cloak>
<p>{{ fullName() }}</p>
<p><a :href="url" target="_blank">Google</a></p>
<p>{{ raw_url }}</p>
<p v-html="raw_url"></p>
<p>{{ age }}</p>
<hr />
<label>First Name</label>
<input type="text" v-model="firstName">
<br />
<br />
<label>Last Name</label>
<input type="text" :value="lastName" @input.prevent="updateLastName('Last name event triggered!', $event)">
<br />
<br />
<button type="button" @click="increment">Increment</button>
<button type="button" @click="age--">Decrement</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.6/vue.global.prod.min.js"></script>
<script src="app.js"></script>
</body>
</html>
const vm = Vue.createApp({
data() {
return {
firstName: 'John',
lastName: 'Doe',
url: 'https://google.com',
raw_url: '<a href="https://google.com" target="_blank">Google</a>',
age: 20,
}
},
methods: {
fullName() {
return `${this.firstName} ${this.lastName.toUpperCase()}`
},
increment() {
this.age++;
},
updateLastName(msg, event) {
console.log(msg, event)
this.lastName = event.target.value;
},
}
}).mount('#app');
[v-cloak] {
display: none;
}