Vue.js 3中状态属性未定义时如何显示默认占位符?
Vue3表格缺失数据显示'-'的实现方案
针对你的需求,完全可以通过模板层面的语法实现,下面提供几种实用的方案:
方案一:使用可选链+空值合并操作符(最简洁)
Vue3模板支持ES6+的可选链操作符(?.)和空值合并操作符(??),可以直接在插值表达式里处理,无需额外指令,代码更简洁:
<template> <tbody class="text-center"> <tr class="table-default"> <th scope="row">Origin</th> <td>{{ $store.state.output[0]?.address ?? '-' }}</td> <td>{{ $store.state.output[0]?.distance ?? '-' }}</td> <td>{{ $store.state.output[0]?.fuelCost ?? '-' }}</td> </tr> <!-- 循环渲染后续行,避免重复硬编码 --> <tr v-for="(item, index) in $store.state.output.slice(1, 4)" :key="index + 1"> <th scope="row">{{ index + 1 }}</th> <td>{{ item?.address ?? '-' }}</td> <td>{{ item?.distance ?? '-' }}</td> <td>{{ item?.fuelCost ?? '-' }}</td> </tr> </tbody> </template>
?.:如果前面的对象/值不存在(undefined/null),会直接返回undefined,不会抛出错误??:当左侧值为undefined或null时,返回右侧的'-'
方案二:使用v-if/v-else显式判断
如果你更倾向于用v-if/v-else的方式控制显示,可针对每个单元格单独判断:
<template> <tbody class="text-center"> <tr class="table-default"> <th scope="row">Origin</th> <td> <span v-if="$store.state.output[0] && $store.state.output[0].address">{{ $store.state.output[0].address }}</span> <span v-else>-</span> </td> <td> <span v-if="$store.state.output[0] && $store.state.output[0].distance">{{ $store.state.output[0].distance }}</span> <span v-else>-</span> </td> <td> <span v-if="$store.state.output[0] && $store.state.output[0].fuelCost">{{ $store.state.output[0].fuelCost }}</span> <span v-else>-</span> </td> </tr> <tr v-for="(item, index) in $store.state.output.slice(1, 4)" :key="index + 1"> <th scope="row">{{ index + 1 }}</th> <td> <span v-if="item && item.address">{{ item.address }}</span> <span v-else>-</span> </td> <td> <span v-if="item && item.distance">{{ item.distance }}</span> <span v-else>-</span> </td> <td> <span v-if="item && item.fuelCost">{{ item.fuelCost }}</span> <span v-else>-</span> </td> </tr> </tbody> </template>
这种方式逻辑直观,适合需要精细控制显示的场景。
额外优化:抽离重复逻辑(可选)
如果表格行数较多,建议把判断逻辑抽成组件方法,减少模板冗余:
<template> <tbody class="text-center"> <tr class="table-default"> <th scope="row">Origin</th> <td>{{ getValue($store.state.output[0], 'address') }}</td> <td>{{ getValue($store.state.output[0], 'distance') }}</td> <td>{{ getValue($store.state.output[0], 'fuelCost') }}</td> </tr> <tr v-for="(item, index) in $store.state.output.slice(1, 4)" :key="index + 1"> <th scope="row">{{ index + 1 }}</th> <td>{{ getValue(item, 'address') }}</td> <td>{{ getValue(item, 'distance') }}</td> <td>{{ getValue(item, 'fuelCost') }}</td> </tr> </tbody> </template> <script> export default { name: 'LineResultTable', methods: { getValue(obj, key) { return obj?.[key] ?? '-' } } } </script>
内容的提问来源于stack exchange,提问作者João Denari
相关产品推荐
相关产品推荐

