Vue v-for遍历对象重复生成th及访问@前缀属性问题咨询
问题1:v-for重复生成表头且单元格无输出
原因
你当前的impreses是单个JSON对象而非数组,Vue的v-for指令遍历对象时,会默认遍历对象的所有属性值,你的返回对象刚好包含6个属性,因此会循环渲染6次完整的<table>标签(包含表头)。
同时循环过程中拿到的item实际是每个属性的值(比如第一个item是字符串CLLLCA82R69D960T),自然不存在codice_fiscale这类子属性,因此单元格无内容。
而你直接写{{impreses.codice_fiscale}}是直接读取原对象的属性,所以可以正常显示。
解决办法
如果你确定接口只会返回单条数据,直接去掉v-for="item in impreses"即可,表格里的变量直接用impreses.xxx读取:
<!-- Show Negativita Check Azienda --> <table class="divide-y divide-gray-200 table-fixed w-full mt-4" v-if="showTableAzienda"> <thead class="bg-gray-900"> <tr> <th>Codice Fiscale</th> <th>Flag Domande</th> <th>Flag Pregiudizievoli</th> <th>Flag Procedure</th> <th>Flag Protesti</th> <th>Data Evasione</th> </tr> </thead> <tbody class="text-center py-6" > <tr> <td>{{impreses.codice_fiscale}}</td> <td>{{impreses.flagDomande}}</td> <td>{{impreses.flagPregiudizievoli}}</td> <td>{{impreses.flagProcedure}}</td> <td>{{impreses.flagProtesti}}</td> <td>{{impreses.dataEvasione}}</td> </tr> </tbody> </table>
如果后续接口可能返回多条数据,把接口返回的单个对象包裹成数组即可,比如拿到返回值后赋值为impreses = [res.data]。
问题2:读取含特殊字符@attributes的属性值
原因
JavaScript的点语法只支持读取符合变量命名规范的属性名,@属于特殊字符,不能直接用点语法读取。
解决办法
使用方括号语法读取特殊命名的属性,把属性名用引号包裹放在方括号中即可,示例写法:
// 读取cognome字段 item.EventiNegativiPersona.InfoPersona.Nominativo['@attributes'].cognome // 读取flagPresenza字段 item.EventiNegativiPersona.ElencoProtesti['@attributes'].flagPresenza
对应模板里的插值写法:
{{ item.EventiNegativiPersona.InfoPersona.Nominativo['@attributes'].cognome }}
内容的提问来源于stack exchange,提问作者Qasim Ali
相关产品推荐
相关产品推荐

