【问题标题】:How to pass a Vue prop into a child component while using v-for?使用 v-for 时如何将 Vue 道具传递给子组件?
【发布时间】:2020-04-30 16:49:04
【问题描述】:

在使用 v-for 时将 Vue 道具传递给子组件时,子组件出现在页面上但不显示该道具。浏览器控制台中没有错误。任何帮助将不胜感激。

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

接收道具的组件:

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

【问题讨论】:

  • 使用v-bind:key="index" 作为user 的道具

标签: vue.js v-for prop


【解决方案1】:

您需要将道具放在导出默认值中。你也不能拥有同名的道具和数据。

这是你可以做的

export default {
    props: ['username'],

    data() {
      return {
         show: true
     }      
  }

您的第一个组件中也不需要数据用户名,如果在参与者中定义,用户名将传递给用户

【讨论】:

    【解决方案2】:

    你有多个username

    1.username 在迭代 participants 属性。

    1. username data 中的变量

    似乎template 部分正在尝试使用您为空的数据部分。

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

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

    也尝试将key 属性添加到您的user 元素。 vue最新版本要求使用key

    所以你的模板如下:

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

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2021-12-02
      • 2019-12-27
      • 2017-05-15
      • 2018-11-08
      • 2019-11-12
      • 2018-07-07
      • 2020-12-19
      相关资源
      最近更新 更多