首页 > 解决方案 > 如何将数据传递给子组件并在子组件中呈现?

问题描述

我正在尝试将数组从父级传递给子级,但在子级而不是父级中渲染/输出它。在我发现的教程中,我只能在父级中渲染数组。例如,我有以下内容:

孩子

<template>
    <div>
        {{tile.name}} {{formattedPoints}}
    </div>
</template>

<script>
    export default {
        props: {
            tile: {
                required: true,
                type: Object
            }
        },
        
        computed: {
            formattedPoints() {
                return this.tile[0].name = 5
            }
        }
    }
</script>

父母

<template>
    <div>
        <User v-for="tile in tileMenu" :key="tile.id" :tile="tile" />
    </div>
</template>

<script>
    import User from './Home.vue'
    import { ref } from 'vue'

    export default {
        components: {
            User
        },

        setup() {
            const tileMenu = ref([
                { id: 1, name: 'tile1' },
                { id: 2, name: 'tile2' },
            ])
            return { tileMenu }
        }
    }
</script>

在这个例子中,我将与父母一起制作输出,但我喜欢与孩子一起制作。在我的思考过程中,这应该是可能的,因为我将数组传递给子组件,如果我这样称呼它

<template>
    <div>
        {{tile[0].name}} 
    </div>
</template>

它应该给我子组件的输出。但这什么也没输出。我该如何解决这个问题?提前致谢

标签: javascriptvue.js

解决方案


我可以建议你(并且 id 需要是唯一的,因为它是你在 for 循环中的关键)

家长:

<template>
  <div>
    <User :tileMenu="tileMenu" /> <!--pass all array-->
  </div>
</template>

<script>
import User from "./Home.vue";

const tileMenu = [
  { id: 1, name: "tile1NAME" },
  { id: 2, name: "tile2NAME" },
];

export default {
  components: {
    User,
  },
  data() {
    return {
      tileMenu: tileMenu,
    };
  },
};
</script>

孩子:

<template>
  <div>
    <div v-for="tile in tileMenuChild" :key="tile.id">
      {{ tile.name }} with id {{ tile.id }}
    </div>
  </div>
</template>

<script>
export default {
  props: {
    tileMenu: Array,
  },
  data() {
    return {
      tileMenuChild: this.tileMenu,
    };
  },
};
</script>

推荐阅读