如何解决我如何在 VueJS 的 HTML 和脚本的其他部分使用来自 API 响应的 id
我试图在不使用任何硬代码的情况下使我的代码动态化。为此,我想使用来自 API 的 id。
这是我的 API 响应:[/infos]
[
...
{
"id": 7,"name": "Highway","price": "High","min": "785","max": "1856","tag": null,},{
"id": 8,"name": "Lowway","price": "low","min": "685","max": "1956",}
...
]
这是我的 Component.vue:
<div class="vx-row">
<div class="vx-col w-full md:w-1/2 mb-base" v-for="info in infos" :key="info.id">
<vx-card>
<div class="header">
<div class="left">
<img src="./img/info_8_logo.png" alt=""/> <-- Hard coded value ie 8
<b>{{info.name}}</b>
</div>
<div class="right">
<vs-button @click="$router.push({name: 'letsCheck',params: {viewContentId: '8' }}).catch(err => {})">Explore</vs-button>
<-- Above as a Hard-coded value ie 8 -->
{{mes.this_is_showing_only_data_of_id8}}
</div>
</div>
</vx-card>
</div>
</div>
<script>
infos: [],mes: []
...
created () {
this.$http.get('/infos')
.then((response) => { this.infos = response.data })
.catch((error) => { console.log(error) })
this.$http.get('/messages/8/tick') <-- Hard coded value
.then((response) => { this.mes = response.data })
.catch((error) => { console.log(error) })
}
</script>
你可以看到我的 Component.vue,我显示了 8 张卡片,每张卡片都显示相同的内容,因为我将 id 硬编码为 8。所以我想知道如何使用来自 API 响应的 id HTML 和其他脚本中的 /infos 端点。
还要注意,来自 API 的 id 只是一个数字,所以我想知道如何将其转换为字符串。然后如何在其他 HTML 和脚本中使用它。
请帮我解决这个问题,我想把来自 API 的 id 放到我在 Component.vue 中所做的任何评论中。
解决方法
这里的最佳实践,您需要为您的消息创建一个新组件,并在组件中作为道具传递 id 并使用此 id 动态构建消息组件。 消息.vue
<template>
<div class="right">
<vs-button @click="$router.push({name: 'letsCheck',params: {viewContentId: id }}).catch(err => {})">Explore</vs-button>
{{mes.my_key_name}}
</div>
</template>
<script>
mes: []
...
props: {
id: {
type: String,required: true,},created () {
this.$http.get(`/messages/this.id/tick`)
.then((response) => { this.mes = response.data })
.catch((error) => { console.log(error) })
}
</script>
App.vue 将是:
<div class="vx-row">
<div class="vx-col w-full md:w-1/2 mb-base" v-for="info in infos" :key="info.id">
<vx-card>
<div class="header">
<div class="left">
<img :src="`./img/info_${info.id}_logo.png`" alt=""/>
<b>{{info.name}}</b>
</div>
<message :id="info.id.toString()"></message>
</div>
</vx-card>
</div>
</div>
<script>
infos: [],...
created () {
this.$http.get('/infos')
.then((response) => { this.infos = response.data })
.catch((error) => { console.log(error) })
</script>
我相信我更新了所有硬编码值,并且我按照您的要求将信息 ID 转换为字符串。
请告诉我:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。