如何解决在 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>
问题
- 我的 SettingsCard.vue 组件中有
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"
>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。