在Vue.js中,组件是可复用的Vue实例,它可以封装特定的功能和界面,并能在应用程序中多次使用。组件允许您将应用程序拆分为多个小的、独立的部分,每个部分都有自己的模板、逻辑和样式。
之前处理多个用户数据时,每个用户都有一个show detail
按键,使用v-for遍历所有数据后,需要给每个用户的how detail
按键加上不同的data的返回值,以及在按下按键时需要判断是哪个用户的操作,不然的话按下按钮后所有用户的detail
都会被展示。当用户越来越多时,这样做很麻烦,使用组件便可以解决这一问题,这样每个用户都有自己独立的逻辑。
const app = Vue.createApp({data() {return {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,stage: "Hide",friend: {id: "manuel",name: "Manuel Lorenzo",phone: "01234 5678 991",email: "manuel@localhost.com",},}},methods: {toggleDetails() {this.detailsAreVisible = !this.detailsAreVisible},},
})app.mount("#app")
如上所示:将原来的<li v-for="friend in friends" :key=friend.id>
中的属性删除,其余html部分放入template
,便完成了一个组件。