html 은 다음과 같음
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>FriendList</h1>
</header>
<section id="app">
<ul>
<li v-for="friend in friends" :key="friend.id">
<h2>{{ friend.name }}</h2>
<button @click="toggleDetails()">
{{ detailsAreVisible ? 'Hide' : 'Show' }} Details
</button>
<ul v-if="detailsAreVisible">
<li><strong>Phone:</strong>{{ friend.phone }}</li>
<li><strong>Email:</strong>{{ friend.email }}</li>
</ul>
</li>
</ul>
</section>
</body>
</html>
vue.js 구성은 다음과 같음
const app = Vue.createApp({
data() {
return {
detailsAreVisible: false,
friends: [
{
id: "manuel",
name: "manuel lorenz",
phone: "01234 5678 991",
email: "manuel@localhost.com",
},
{
id: "julie",
name: "Julie Jones",
phone: "09876 543 221",
email: "julie@localhost.com",
},
],
};
},
methods: {
toggleDetails() {
this.detailsAreVisible = !this.detailsAreVisible;
}
}
});
app.mount("#app");
여기서 문제는
클릭시
개별적으로 Detail을 보여주는 것이 아닌 전체를 보여주도록 코드가 되어 있다는 부분이다.
이를 해결하기 위하여 vue에서는 component 구성 요소를 추가할 수 있다.
app.component() 를 구성한다.
const app = Vue.createApp({
data() {
return {
detailsAreVisible: false,
friends: [
{
id: "manuel",
name: "manuel lorenz",
phone: "01234 5678 991",
email: "manuel@localhost.com",
},
{
id: "julie",
name: "Julie Jones",
phone: "09876 543 221",
email: "julie@localhost.com",
},
],
};
},
});
app.component("friend-contact", {
template: `
<li>
<h2>{{ friend.name }}</h2>
<button @click="toggleDetails()">
{{ detailsAreVisible ? 'Hide' : 'Show' }} Details
</button>
<ul v-if="detailsAreVisible">
<li><strong>Phone:</strong>{{ friend.phone }}</li>
<li><strong>Email:</strong>{{ friend.email }}</li>
</ul>
</li>
`,
data() {
return {
detailsAreVisible: false,
friend: {
id: "manuel",
name: "manuel lorenz",
phone: "01234 5678 991",
email: "manuel@localhost.com",
},
};
},
methods: {
toggleDetails() {
this.detailsAreVisible = !this.detailsAreVisible;
}
}
});
app.mount("#app");
app.component("friend-contact"
여기서 friend-contact로 태그를 만든다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>FriendList</h1>
</header>
<section id="app">
<ul>
<friend-contact></friend-contact>
</ul>
</section>
</body>
</html>
이렇게 하면 각 ul에 대한 독립적인 객체가 된다.
만약 동일한 태그를 두번 달
<ul>
<friend-contact></friend-contact>
<friend-contact></friend-contact>
</ul>
동일한 내용이지만 별도로 동작하는 것을 볼 수 있다.