[英]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.