10. passing on data with events
์ฃผ์
์ด ๊ฐ์์์๋ ์ด๋ฒคํธ์ ํจ๊ป ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ์ ๋น ๋ฅด๊ฒ ์ดํด๋ด ๋๋ค. ์๋ฅผ ๋ค์ด, ์ฝ์์ ๋ก๊ทธ๋ฅผ ์ถ๋ ฅํ๋ ๊ฐ๋จํ ๋ฉ์์ง๋ฅผ ์ด๋ฒคํธ์ ํจ๊ป ์ ๋ฌํ๋ ๋ฐฉ๋ฒ์ ์ค๋ช ํฉ๋๋ค. ํ ํ๋ฆฟ์ ๋๋ ํฐ๋ธ ์์์ "Last name event triggered"๋ผ๋ ๋ฉ์์ง๋ฅผ ์ ๋ฌํ๋ ค๊ณ ํฉ๋๋ค. ๊ทธ๋ฌ๋ ์ด๊ฒ์ ํจ์๊ฐ ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๊ธฐ๋ํ๊ณ ์๊ธฐ ๋๋ฌธ์ ํจ์๋ฅผ ๊นจ๋จ๋ฆด ์ ์์ต๋๋ค. ํจ์์ ์ธ์๋ฅผ ์ ๋ฌํ์ง ์์ผ๋ฉด Vue๊ฐ ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ์๋์ผ๋ก ์ ๋ฌํ์ง๋ง, ์ฐ๋ฆฌ๊ฐ ์์ฒด ์ธ์๋ฅผ ์ ๋ฌํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ์๋์ผ๋ก ์ ๋ฌํด์ผ ํฉ๋๋ค.
์ด๋ฒคํธ ๊ฐ์ฒด๋ ํน๋ณํ ์ด๋ฆ์ธ $event๋ก ์ง์ ๋ฉ๋๋ค. ํ ํ๋ฆฟ์์ ์ด๋ฒคํธ์ ๊ด๋ จ๋ ๋ฐ์ดํฐ๋ฅผ $event ๊ฐ์ฒด์ ์ ์ฅํฉ๋๋ค. ์ดํ์๋ ์ ํ๋ฆฌ์ผ์ด์ ๋ด์ ํจ์๋ฅผ ์ ๋ฐ์ดํธํ์ฌ ์ ์ธ์๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค. ์๋ฅผ ๋ค์ด, updateLastName ํจ์์์ ์ฒซ ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ฅผ ๋ฉ์์ง๋ก, ๋ ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ฅผ ์ด๋ฒคํธ๋ก ์ค์ ํฉ๋๋ค. ํจ์ ๋ด์์ ๋ฉ์์ง ๋งค๊ฐ๋ณ์๋ฅผ ๋ก๊ทธํ๊ณ , ๊ธฐ๋ณธ ์ด๋ฒคํธ ๋์์ ๋ฐฉ์งํฉ๋๋ค.
ํ์ด์ง๋ฅผ ์๋ก๊ณ ์นจํ๊ณ ์ฝ์์ ์ด๋ฉด ์ ๋ ฅํ ๋ด์ฉ์ ๋ฐ๋ผ ๋ง์ง๋ง ์ด๋ฆ์ด ์ ๋ฐ์ดํธ๋๊ณ ํจ์์ ์ ๋ฌํ ๋ฉ์์ง๊ฐ ๋ก๊ทธ๋ฉ๋๋ค. ์ด๋ ๊ฒ ํ๋ฉด ์ธ์๋ฅผ ์ ๋ฌํ์ฌ ์ด๋ฒคํธ ํธ๋ค๋ฌ์ ๋์์ ์ฌ์ฉ์ ์ ์ํ ์ ์์ต๋๋ค. ์ถ๊ฐ์ ์ธ ์ธ์๋ฅผ ์ถ๊ฐํ๋ ค๋ฉด ํจ์๋ฅผ ์ ๋ฐ์ดํธํ์ฌ ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ์์ฉํ๋๋ก ํด์ผ ํฉ๋๋ค. 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="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) {
event.preventDefault();
console.log(msg, event)
this.lastName = event.target.value;
},
}
}).mount('#app');
[v-cloak] {
display: none;
}