如何在使用v-for时将Vue道具传递到子组件中?

问题描述 投票:0回答:2

当使用v-for时,将Vue道具传递到子组件中时,子组件会出现在页面上,但不显示该道具。浏览器控制台中也没有出现任何错误。如果有任何帮助,我们将非常感激。

传递道具的组件。

<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>

接收道具的组件

<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>
vue.js v-for prop
2个回答
1
投票

你需要把道具放在导出默认里面。另外,你不能有一个道具和数据的名称相同。

这是你可以做什么

export default {
    props: ['username'],

    data() {
      return {
         show: true
     }      
  }

你也不需要在你的第一个组件中使用数据的用户名,如果在participants中定义了用户名,那么用户名就会传递给用户。


1
投票

你有多个 username:

1.username 在迭代中 participants

  1. username 中的变量 data

看来 template 部分试图使用你的数据部分,而这部分是空的。

你需要删除第二个部分。所以你的数据会变成这样。

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

也可以试着添加一个 keyuser 元素也。它已被要求使用 key 在最新版本的vue中。

所以你的模板会像下面这样。

<user 
        v-for="(username, index) in participants"
        v-bind:username="username"
        v-bind:index="index"
        v-bind:key="`user-${index}`"
/>
© www.soinside.com 2019 - 2024. All rights reserved.