我有一个使用 Vuetify 的数据表,它从 Rails 后端传递 localAuthority 属性。一切都运行得很好,直到我传递一个空的子关联(嵌套属性)。在本例中为“县”:
<script>
import axios from "axios";
export default {
name: 'LocalAuthorityIndex',
props: {
localAuthorities: {type: Array, default: () => []},
counties: {type: Array, default: () => []},
localAuthorityTypes: {type: Array, default: () => []}
},
data() {
return{
search: '',
dialog: false,
testmh: 'hello',
dialogDelete: false,
headers: [
{ text: 'Name', align: 'start', value: 'name' },
{ text: 'ONS Code', value: 'ons_code' },
{ text: 'ID', value: 'id' },
{ text: 'Population', value: 'population' },
{ text: 'county', value: 'county.name' },
{ text: 'Website', value: 'website' },
{ text: 'Actions', value: 'actions', sortable: false },
],
因此,在上面的示例中,只要所有记录都有县关联 (belongs_to),它就可以工作。但是,如果一条记录没有与之关联的“县”,那么我会收到以下错误:
[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
我尝试了很多方法,例如添加条件语句,如下所示:
{ text: 'county', value: ('county.name' ? 'county.name' : nil )},
但似乎没有任何效果。
最佳答案
根据您的<v-data-table>
Codepen 上的代码,我发现您正在用自己的项目覆盖默认的表格项插槽。
您的错误来自这部分代码:
...
<template #item.county.name="{ item }">
<a :href="'/counties/' + item.county_id">
{{ item.county.name }}
</a>
</template>
...
看一下第一个字符串。 #item.county.name
是 v-slot:item.county.name
的缩写形式来自 headers
中的字符串之一数组:
...
{ text: 'county', value: 'county.name' },
所以没有错误,即使您的item不包含任何county,这部分也会被vuetify库正确解析。
错误出现在上述代码的第三个字符串中。您正在尝试打印county的名称而不检查其是否存在。这就是为什么你会得到 ...Cannot read properties of undefined...
错误。
我想你可以这样解决你的问题:
<template #item.county.name="{ item }">
<a :href="'/counties/' + item.county_id">
{{ item.county ? item.county.name : 'No name' }}
</a>
</template>
当然,如果您需要在这种情况下隐藏县链接,您也可以添加 v-if
(或 v-show
)进入 a
标签。
我还创建了 a small Codepen一些静态数据。看看这个 Playground 中的 item.name.text 插槽,也许它会帮助您理解类似的对象关联。
关于javascript - Vuetify 数据表 header 数组不接受空子关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70221636/