Last active
August 25, 2021 09:34
-
-
Save admench/77d430d71fc6f1e2dd30243b379dcc07 to your computer and use it in GitHub Desktop.
A demonstration of the vue component provider pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div v-for="card in results"> | |
<card-provider :card="card"> | |
<template v-slot="cardProps"> | |
<card v-bind="cardProps" /> | |
</template> | |
</card-provider> | |
</div> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<slot v-bind:cardProps="cardProps" /> | |
</template> | |
<script> | |
name: 'CardProvider', | |
props: { | |
card: { | |
type: Object, | |
required: true | |
} | |
}, | |
computed: { | |
cardProps() { | |
// ensure keys of this object match the card component prop names | |
return { | |
cardTitle: this.title, | |
// conditional object properties: | |
...(this.card.model !== 'author' && this.footerTitle) | |
} | |
}, | |
title () { | |
return this.card.model === 'author' ? this.card.full_name : this.card.title | |
}, | |
footerTitle () { | |
// this object will be merged directly into this.cardProps if logic above passes | |
return { | |
// ensure key of this object matches the card component prop names | |
cardFooterTitle: this.card.authors[0].full_name | |
} | |
} | |
</script> |
You could have more than 1 card provider depending on the scenario / part of the app / website.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Conditional Object Properties Using Spread in JavaScript
https://medium.com/@slamflipstrom/conditional-object-properties-using-spread-in-javascript-714e0a12f496