[英]Vuejs How to render a table based on JSON data
我有这个JSON
数组,它看起来像这样:
"data": {
"cells": [
[
{
"rowIndex": 0,
"columnIndex": 0,
"value": "<p>This is some value</p>",
"type": "th",
"scope": "col"
},
{
"rowIndex": 0,
"columnIndex": 1,
"value": "<p>Another value</p>",
"type": "th",
"scope": "col"
}
],
[
{
"rowIndex": 1,
"columnIndex": 0,
"value": "<p>Blabla blabla</p>",
"type": "td",
"scope": null
},
{
"rowIndex": 1,
"columnIndex": 1,
"value": "<p>Lorem ipsum</p>",
"type": "td",
"scope": null
}
]
],
}
现在我想在我的vuejs
-app 的表中呈现这些数据,所以我尝试这样做:
首先通过计算值获取数据:
computed: {
tableData() {
return this.content.data.cells;
},
},
然后通过表格渲染数据:
<table>
<tr v-for="cell in tableData" :key="cell.id">
<template v-if="cell.type === 'th'">
<th v-for="header in cell" :key="header">
{{ header.value }}
</th>
</template>
<template v-if="cell.type === 'td'">
<td v-for="celldata in cell" :key="celldata">
{{ celldata.value }}
</td>
</template>
</tr>
</table>
但这没有显示任何内容,这些字段只是空的。 我究竟做错了什么?
cells
数组的每一行包含一个数组,您必须使用row[0].type
测试行类型{{ }}
是不够的——你需要使用v-html
:key="cell.id"
但我在数据本身中看不到任何id
字段... const data = { "cells": [ [{ "rowIndex": 0, "columnIndex": 0, "value": "<p>This is some value</p>", "type": "th", "scope": "col" }, { "rowIndex": 0, "columnIndex": 1, "value": "<p>Another value</p>", "type": "th", "scope": "col" } ], [{ "rowIndex": 1, "columnIndex": 0, "value": "<p>Blabla blabla</p>", "type": "td", "scope": null }, { "rowIndex": 1, "columnIndex": 1, "value": "<p>Lorem ipsum</p>", "type": "td", "scope": null } ] ], } const vm = new Vue({ el: "#app", data() { return { data } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> <div id="app"> <table class="table is-bordered"> <tr v-for="(row, idx) in data.cells" :key="idx"> <th v-for="cell in row" :is="cell.type" :key="`r${idx}_c${cell.columnIndex}`" v-html="cell.value"> </th> </tr> </table> </div>
您正在使用 JSON 数据。 您确实需要首先使用JSON.parse()
方法将 json 解析回 javascript 数据类型。
您可以在mdn上阅读此内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.