Reputation: 4132
I'm trying to create a simple card component CustomCard.vue and re-use it on HomeComponent.vue page with specified data, so I've created a loop and put the needed data in cards: []
I don't know why it doesn't work. I can see the 3 elements on the page but they are displayed with the default values of the component, instead of taking the data from the cards:[]
.
...
<custom-card v-for="n in cards" :key="n">
<img :src="n.cardImage" alt="">
<p>{{n.cardDesc}}</p>
</custom-card>
...
<script>
export default {
data() {
return {
cardImage: "",
cardDesc: "",
cards: [
{id: "1", cardImage: "../src/assets/img1.jpg", cardDesc: "some description 1"},
{id: "2", cardImage: "../src/assets/img2.jpg", cardDesc: "some description 2"},
{id: "3", cardImage: "../src/assets/img3.jpg", cardDesc: "some description 3"}
]
}
}
}
</script>
<template>
<div>
<img :src="cardImage" alt="">
<p>{{cardDesc}}</p>
</div>
</template>
<script>
export default {
data () {
return {
cardImage: "../src/assets/default.jpg",
cardDesc: "default description text"
}
}
// props: ['cardDesc', 'cardImage']
}
</script>
I want these values below to be the default component values just as a placeholder (so I've put them in components data):
cardImage: "../src/assets/default.jpg",
cardDesc: "default description text"
If I pass the props out, I get an error: [Vue warn]: The data property "cardImage" is already declared as a prop. Use prop default value instead.
So I commented it out for now.
I've registered the CustomCard.vue globally in index.js:
Upvotes: 3
Views: 1742
Reputation: 165065
Your component has no slots so there's no reason to include any content.
Seems to me you just need
<custom-card v-for="card in cards" :key="card.id"
:card-desc="card.cardDesc"
:card-image="card.cardImage" />
Note the key
is set to the actual unique identifier for each iterable element.
You should of course un-comment the props
declaration and remove the conflicting data
keys from your component. As mentioned in the error message, you can also set default values
export default {
props: {
cardDesc: {
type: String,
default: 'default description text'
},
cardImage: {
type: String,
default: '../src/assets/default.jpg'
}
},
data () { // probably don't even need a data property
return {}
}
}
Upvotes: 1