<template>
<div class="overlay_CompareItem"></div>
<div class="modal_CompareItem">
<header class="modal__header_CompareItem">
<h2>Compare Computers</h2>
<button @click=(closeModal) class="close-button_CompareItem">×</button>
</header>
<main class="modal__main_CompareItem">
<table>
<thead>
<tr>
<td>
Brand
</td>
</tr>
</thead>
<tbody>
<tr :key="index" v-for="(compareThis, index) in list_of_computers">
<td>{{compareThis.brand}}</td>
</tr>
</tbody>
</table>
</main>
</div>
<script>
import axios from "axios";
import { ref } from 'vue';
export default {
data() {
return {
list_of_computers: []
}
},
mounted() {
this.fetchComputer(1)
this.fetchComputer(2)
},
methods: {
async fetchComputer(productId) {
const res = await fetch('http://localhost:5030/api/Products/CompareProducts/' + productId);
const finalRes = await res.json();
this.list_of_computers.push(finalRes);
alert(JSON.stringify(this.list_of_computers)); // LINE #1
},
closeModal() {
this.$emit('close');
},
}
}
备注:
上面的第 1 行生成以下数据:
[[{"id":1, "productId":1, "brand":"华硕",...... }], [{"id":2, "productId":2, "brand":"DELL",....... }]]
也许 [[{...}], [{...}]] 不起作用??? 也许 [{...}, {...}] 有效???
如何让我的代码正常工作?
如果我不使用 array.push,那我还能用什么?
或者,我可以尝试其他什么方法?
提前非常感谢您!
饼干
如果
finalRes
是一个数组,并且您想要将其元素推送到 list_of_computers
,而不是将整个数组作为单个元素推送,请将其展开到 push
操作中:
this.list_of_computers.push(...finalRes);