我用的是vue,来自反应背景。React有一个名为.map的方法,如果您将一个数组作为支持传递,那么它将根据数组中的项目数多次呈现该组件,并从索引中提取每个数据。如下所示:
function App() {
const classes = useStyles();
const [finance, setFinance] = useState([]);
useEffect(() => {
axios
.all([
axios.get(
`https://cloud.iexapis.com/stable/stock/market/collection/list?collectionName=gainers&token=XXXXXXXXXXXXXXXXXXXXX`
),
])
.then((res) => {
setFinance(res[0].data);
})
.catch((err) => {
console.log(err);
});
}, []);
const cardList = finance.map((company, index) => (
<Grid item xs={10} sm={5} md={4} lg={3} xl={2}>
<Cards company={company} index={index} />
</Grid>
));基本上,finance是存储来自数组的所有数据的状态。我将company的数据作为支柱传递给Cards组件。这是可行的,我试图在vue中复制这一效果。到目前为止,我的代码如下:
<template>
<v-container>
<v-row align="start" justify="center">
<v-col xs="12" sm="6" md="4" lg="3">
<cards :crypto="crypto[0]" />
</v-col>
</v-row>
</v-container>
</template>
<script>
import cards from "@/components/cards.vue";
export default {
data() {
return {
crypto: []
};
},
components: { cards },
mounted() {
this.axios
.get(
"https://min-api.cryptocompare.com/data/top/totalvolfull?limit=20&tsym=USD&api_key=xxxxxxxxxxxxxxxxxxx"
)
.then(response => {
this.crypto = response.data.Data;
console.log(response.data.Data);
})
.catch(error => console.log(error));
}
};
</script>如您所见,crypto是我在Vue中的cards组件中传递的一个数据属性。我想要做的是完全相同的反应,而我传递一个对象数组到一个组件,并且组件呈现多次取决于数组的对象数量,同时从相应的索引获取数据。我试过做v指令,但我认为这只适用于列表?任何帮助都是非常感谢的。
注意:这是用于上下文的my项目的Card组件:
<template>
<v-card class="mx-auto" max-width="344" outlined>
<v-list-item three-line>
<v-list-item-content>
<div class="overline mb-4">{{ crypto.CoinInfo.FullName }}</div>
<v-list-item-title class="headline mb-1">{{
crypto.CoinInfo.Name
}}</v-list-item-title>
<v-list-item-subtitle
>Price: {{ crypto.DISPLAY.USD.PRICE }}<br />Change :
{{ crypto.DISPLAY.USD.CHANGEDAY }}</v-list-item-subtitle
>
</v-list-item-content>
<!-- <v-list-item-avatar tile size="80" -->
<img
style="height: 80px;"
:src="`https://www.cryptocompare.com/${crypto.CoinInfo.ImageUrl}`"
/>
<!-- </v-list-item-avatar> -->
</v-list-item>
<v-card-actions>
<v-btn text>Save</v-btn>
<v-btn text>Check</v-btn>
</v-card-actions>
</v-card>
</template>
<script>
export default {
props: {
crypto: Object
}
};
</script>发布于 2020-10-31 06:26:22
使用Vue CLI生成的项目也可以使用函数,它允许您执行类似于React解决方案的操作。这不一定是一个“更好”的解决方案比使用v-for,但只是一个替代选项,如果您喜欢JSX。
例如,容器组件可以获取数据,并将结果分配给绑定到CardList组件的支柱,后者将支柱映射到Card组件的数组:
Container.vue
<template>
<CardList :crypto="crypto" />
</template>
<script>
export default {
async mounted() {
const { data } = await axios.get(...)
this.crypto = data
}
}
</script>CardList.vue
<script>
export default {
props: {
crypto: {
type: Array,
required: true,
default: () => [],
},
},
render() {
return (
<v-container>
<v-row align="start" justify="center">
<v-col xs="12" sm="6" md="4" lg="3">
{ this.crypto.map(crypto => <Card crypto={crypto} />) }
</v-col>
</v-row>
</v-container>
)
},
};
</script>https://stackoverflow.com/questions/64618534
复制相似问题