65535
65535

Reputation: 553

How to pass a Vue prop into a child component while using v-for?

When passing a Vue prop into a child component while using v-for, the child component appears on the page but does not display the prop. There are no errors present in the browser console. Any help would be greatly appreciated.

The component passing the prop:

<template>
    <div class="col" ref="participants-window">
        
    <div>
        <user 
        v-for="(username, index) in participants"
        v-bind:username="username"
        v-bind:index="index"
        > </user>
    </div>     
    </div>
</template>

<script>
export default {
    props: ['participants'],
    
    data() {
      return {
         show: true,
         username: null
     }      
},
    
    mounted() {
    this.scrollToBottom();
},

watch: {
    messages() {
        this.scrollToBottom();
    }
},

methods: {
    scrollToBottom() {
        this.$nextTick(() => {
            this.$refs['participants-window'].scrollTop = this.$refs['participants-window'].scrollHeight;
        });
    }
},
} 

</script>

<style scoped>

.col {
    overflow-y: auto;
    max-height: 200px;
    word-wrap: break-word;
}
</style>

The component receiving the prop:

<template>
  <div class="text-center">
  <b-button id="tooltip-button-2" variant="primary">{{ username }}</b-button>
  <b-tooltip show target="tooltip-button-2">tooltip</b-tooltip>
  </div>
</template>
<script>

 props: ['username']

  export default {
    data() {
      return {
         show: true,
         username: null
     }      
  }
}
</script>

Upvotes: 0

Views: 1570

Answers (2)

Alireza HI
Alireza HI

Reputation: 1933

You have multiple username:

1.username in iterating the participants prop.

  1. username variable in data

It seems that the template part is trying to use your data part which is null.

You need to remove the second one. So your data will become like this:

export default {
    data() {
      return {
         show: true,
     }      
}

Also try to add a key prop to your user element too. It has been required to use key in latest version of vue.

So your template would be like below:

<user 
        v-for="(username, index) in participants"
        v-bind:username="username"
        v-bind:index="index"
        v-bind:key="`user-${index}`"
/>

Upvotes: 2

Hides
Hides

Reputation: 546

You need to put props inside the export default. Also you can't have a prop and data with the same name.

This is what you can do

export default {
    props: ['username'],

    data() {
      return {
         show: true
     }      
  }

You also don't need the data username in your first component, the username will pass to user if defined in participants

Upvotes: 1

Related Questions