步骤
1、新建src/componets/FriendContact.vue
<template>
<li>
<h2>{{friend.name}}</h2>
<button @click="toggleDetails">Show Details</button>
<ul v-if="detailsVisiable">
<li><strong>Phone:</strong>{{ friend.phone }}</li>
<li><strong>Email:</strong>{{ friend.email }}</li>
</ul>
</li>
</template>
<script>
export default {
data() {
return {
detailsVisiable: false,
friend: {
name: "John Doe",
phone: "123-456-7890",
email: "john@example.com",
},
};
},
methods:{
toggleDetails() {
this.detailsVisiable = !this.detailsVisiable;
},
}
};
</script>
2、更新main.js
import { createApp } from 'vue'
import App from './App.vue'
import FriendContact from './components/FriendContact.vue';
const app = createApp(App);
app.component('friend-contact', FriendContact);
app.mount('#app');
3、App.vue中添加<friend-contact>组件
<template>
<section>
<h2>My Friends</h2>
<ul>
<friend-contact></friend-contact>
<friend-contact></friend-contact>
</ul>
</section>
</template>
<script>
// const app = {
export default {
data() {
return {
friends: [
{ id: 1, name: 'John', phone: '1234567890', email: 'john@gmail.com' },
{ id: 2, name: 'Jane', phone: '0987654321', email: 'jane@gmail.com' },
{ id: 3, name: 'Bob', phone: '1245678901', email: 'bob@gmail.com' },
{ id: 4, name: 'Alice', phone: '0123456789', email: 'alice@gmail.com' },
{ id: 5, name: 'Jack', phone: '1029384756', email: 'jack@gmail.com' },
{ id: 6, name: 'Jill', phone: '1234567890', email: 'jill@gmail.com' }
]
}
}
}
</script>