【发布时间】:2019-06-07 19:34:39
【问题描述】:
我使用 v-for-loop 来渲染任意数量的组件,基于之前对 Rails 后端的 API 调用。现在我将响应作为对象数组存储在我的“母组件”的数据中,我想从中将道具传递给子组件。我怎样才能做到这一点?恐怕我无法找到解决方案。
我尝试了几种访问数据中数组的表示法,其中大多数最终都会引发编译错误。
<template>
<div class="row">
<GameCard v-for="boardgame in boardgames"
:key="id"
:gameRating="gameRating"
:gameTitle="boardgame.title"
:gameDescription="boardgame.description"
:gameImage="boardgame.cover_image_url"
:gamePlayerCount="boardgame.gamePlayerCount"
:gameDuration="boardgame.gameDuration"
/>
</div>
</template>
<script>
import axios from 'axios';
import GameCard from '../GameCard/GameCard';
export default {
data() {
return {
boardgames: []
}
},
created() {
axios.get('http://localhost:3001/api/v1/boardgames/')
.then(response => {
console.log(response.data)
const data = response.data
const fetchedBoardgames = []
for (let key in data) {
const boardgame = data[key]
boardgame.id = key
fetchedBoardgames.push(boardgame)
}
this.boardgames = fetchedBoardgames
})
.catch(error => console.log(error))
},
components: {
GameCard,
}
};
</script>
<style lang="scss">
</style>
这是子组件代码:
<template>
<div class="col">
<article class="card gamecard">
<a href="">
<div class="card image-wrapper">
<img class="card-img-top" src="https://via.placeholder.com/250x250.jpg" alt=""/>
</div>
<RatingBadge :gameRating="gameRating"/>
<div class="gamecard-info-overlay">
<div class="gamecard-essential-info">
<span class="players">{{ gamePlayerCount }}</span>,<span class="duration">{{ gameDuration }}</span>
</div>
</div>
<div class="card-body">
<h3 class="gamecard-card-title">Spieltitel <span>(2019)</span></h3>
<hr class="my-4"/>
<p class="card-text">Lorem ipsum dolor amet brooklyn leggings cloud bread poke snackwave gentrify. Hella farm-to-table brooklyn cray typewriter, beard hoodie mixtape subway tile knausgaard keffiyeh. Palo santo post-ironic irony tumeric actually. Offal tumblr trust fund fixie, cornhole direct trade cliche intelligentsia street art pug fingerstache four dollar toast.</p>
</div>
<GameCardButton />
</a>
</article>
</div>
</template>
<script>
import RatingBadge from './RatingBadge.vue';
import GameCardButton from './GameCardButton.vue';
export default {
props: ['gameRating', 'gameDuration', 'gamePlayerCount'],
components: {
RatingBadge,
GameCardButton,
}
};
</script>
预期结果:我能够从数组中传递任何所需的道具。
【问题讨论】:
-
怎么了?看起来不错
-
当我使用 Chrome 中的 Vue-Dev-Tools 检查子组件时,道具以某种方式设置为 undefined。
-
请提供子组件的代码
-
我更新了帖子,感谢您的浏览!
-
您还传递了未在子组件中定义的道具
标签: javascript vue.js vuejs2 vue-component