[英]create a reusable component in vue.js
如何使我的 vue.js 組件更加通用和可重用並且只能傳遞必要的數據?
這就是我想要構建的:
// App.vue
<template>
<div>
<!-- Component A -->
<SettingsCard
:listA="listA"
cardType="CompA"
>
<template v-slot:header>
Foo - Component A
</template>
</SettingsCard>
<!-- Component B -->
<SettingsCard
:listB="listB"
cardType="CompB"
>
<template v-slot:header>
Bar - Component B
</template>
</SettingsCard>
</div>
</template>
// SettingsCard.vue
<template>
<div>
<slot name="header"></slot>
<div v-if="cardType === 'CompA'">
<!-- Show input and submit button for component a -->
</div>
<div v-if="cardType === 'CompB'">
<!-- Show input and submit button for component b -->
</div>
<ListComponent
:cardType="cardType"
:list="computedList"
/>
</div>
</template>
<script>
export default {
props: {
cardType: String, // for the v-if conditions
listA: Array,
ListB: Array
},
data() {
return {
namefromCompA: '', // input from component A
namefromCompB: '' // input from component B
}
},
computed: {
computedList() {
// returns an array and pass as prop the the card footer
}
}
}
</script>
undefined
的道具和unused
的數據// CompA:
props: {
cardType: 'compA',
listA: [1, 2, 3], // comes from the parent
listB: undefined // how to prevent the undefined?
}
// CompA:
data() {
return {
namefromCompA: 'hello world',
namefromCompB: '' // unused - please remove me
}
}
v-if="cardType === 'compA'"
感覺不對您是否有更好的方法來使該組件可重用並刪除任何不必要的東西?
使用方法而不是"cardType === 'CompA'"
。
只需在您的SettingsCard.vue
中嘗試此操作
methods: {
showMeWhen(type) {
return this.cardType === type;
},
},
}
你的 v-if 渲染條件就像: v-if="showMeWhen('compA')"
例如你的namefromCompA/B
你可以傳遞一個新的道具來顯示正確的名字。
props: {
cardType: String, // for the v-if conditions
listA: Array,
ListB: Array,
namefromComponent: {
type: String,
default: 'NoName'
}
},
然后在您的使用中,您只需像使用其他道具一樣傳遞它。
<SettingsCard
:listB="listB"
cardType="CompB"
namefrom-component="my Name for component B"
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.