【问题现象]
Vue中使用v-for
遍历数组时可能会出现两个不同数组间的关联问题,在data
中定义了商品列表brandList
和depList
data: {
// 品牌列表数据
brandList: [
{id: 1, name: '宝马', status: 'true', depId: '101', time: new Date()},
{id: 2, name: '奔驰', status: 'true', depId: '102', time: new Date()},
{id: 3, name: '大众', status: 'true', depId: '103', time: new Date()},
],
depList: [
{id: 101, depName: '厂家1'},
{id: 102, depName: '厂家2'},
]
},
使用v-for
循环遍历输出时,表格中默认呈现的时没有经过匹配的brandList
中的depId
,当加上v-if
的筛选条件后,在遍历时会出现品牌名称为大众
的品牌的厂家没有对应的厂家,导致表格展现异常。
【解决方案】
配置过滤器,使用过滤器对brandList
中的depId
进行转换
- 定义全局变量
that
,便于过滤器选择depList
let that
- 在
beforeCreate
生命周期将this
赋值给that
,通过that
获得depList
beforeCreate: function () {
that = this
},
- 配置过滤器,对
brandList
中的depId
进行转换
depChange(depId){
let depName = '-'
for(let i = 0; i < that.depList.length; i++){
if(depId == that.depList[i].id)
depName = that.depList[i].depName
console.log(depName)
}
return depName
}
- 输出
生产厂家
时,使用过滤器进行输出
<td>
{{brand.depId | depChange}}
</td>
【最终结果]