el.Despertar
el.Despertar

Reputation: 51

How to use array props in Vue 3?

Trying to learn the basics, I got an array in the parent component (App.vue)

data() {
 return {
  fruits: [
    "apple",
    "pear",
    "cherry" 
  ], 
 };
},

I want to be able to have the same component 3 times for each fruit

<Fruit  v-for="(fruit, index) in fruits" :key="index"/>

And this is the props feature Fruit.vue component (the child component)

 props: {
  fruits: {type: Array, required: false},
}

How should I write the code so it displays each fruit in their "own" component in the tag of Fruit.vue

Upvotes: 1

Views: 4796

Answers (1)

andre de waard
andre de waard

Reputation: 164

You want to have a fruit component that accepts only a string from the array.

Fruit component

<template>
<div class="fruit">
{{ props.fruit }} 
</div>
</template>

<script lang="ts"
export default defineComponent({
  props: {
    fruit: { type: String, required: true }
  }
  setup(props) {
    return { props }
  }
}
</script>

inside app.vue

<Fruit  v-for="fruit in fruits" :key="fruit" :fruit="fruit"/>

Upvotes: 2

Related Questions