如何在Vuetify数据表中创建动态项目槽



我正在学习编码并拥有一个Vuetify数据表,我想在其中将表中的布尔值更改为图标。我想使表成为动态的,这样我就可以将它作为一个组件重用,根据页面向它传递道具。我可以将头和其他东西作为道具传递,但将道具传递到子表中的v-slot项是有问题的。

我目前正在从父级传递一个"booleans"道具,它有一个对象数组,包括我想更改为图标和true/false图标的列的名称。

这是来自父级的"boolean"道具数组。为了可读性,我去掉了所有其他内容。

booleans: [
{
name: "wo",
iconTrue: "mdi-account",
iconFalse: "mdi-office-building",
},
{
name: "ep",
iconTrue: "mdi-account",
iconFalse: "mdi-office-building",
}]

子组件是一个vuetify数据表。

<template>
<div>
<v-data-table
:headers="headers"
:items="gotData"
:items-per-page="25"
:sort-by="sort"
dense
:search="search"
:loading="loading"
loading-text="Loading... Please wait"
@click:row="handleClick"
class="elevation-1"
>
<template v-for="(bool, i) in booleans" v-slot:[boolNames[i]]="{ item }">
<v-icon :key="i" class="mr-3">
{{ boolNames[i] ? bool.iconTrue : bool.iconFalse }}</v-icon>
</template>
</v-data-table>
</div>
</template>

编写脚本

<script>
export default {
data: () => ({
search: "",
loading: "true",
dialog: false,
gotData: [],
}),
props: {
dataSource: {
type: String,
},
headers: {
type: Array,
},
tableTitle: {
type: String,
},
pageURL: {
type: String,
},
sort: {
type: String,
},
booleans: {
type: Array,
},
},
created() {
this.initialize();
},
computed: {
formTitle() {
return this.editedIndex === -1 ? "New Item" : "Edit Item";
},
boolNames: function () {
return this.booleans.map(function (bool) {
return "item." + bool.name;
});
},
},
methods: {
async initialize() {
const response = await this.$axios
.$get(this.dataSource)
.then((response) => {
this.gotData = response.data;
})
.catch(function (error) {
console.log(error);
});
this.loading = false;
},
async addItem(item) {
this.editedIndex = this.dataSource.indexOf(item);
this.editedItem = Object.assign({}, item);
this.dialog = true;
this.$axios({
method: "post",
url: this.dataSource,
data: this.item,
})
.then((response) => {
this.gotData = response.data;
})
.catch(function (error) {
console.log(error);
});
},
handleClick(item) {
this.$router.push(this.pageURL + item.id);
},
},
};
</script>

boolNames[i]根据我的意愿返回item.wo和item.ep,但vuetify将它们视为字符串而非道具,因此三进制总是读取true,表中的所有单元格都是true图标。

如果我将item.wo硬编码到模板中,它将正常工作,例如

<template v-for="(bool, i) in booleans" v-slot:[boolNames[i]]="{ item }">
<v-icon :key="i" class="mr-3">
{{ item.wo ? bool.iconTrue : bool.iconFalse }}</v-icon>
</template>

我试过各种其他方法来实现这一点,但都想不通。

我该如何让它发挥作用?

好的,想好了。我去掉了计算属性,回到了开始的状态。只是有一个语法错误。以下是有效的代码。

<template
v-for="(bool, i) in booleans"
v-slot:[`item.${bool.name}`]="{ item }"
>
<v-icon :key="i" class="mr-3">
{{ item[bool.name] ? bool.iconTrue : bool.iconFalse }}</v-icon
>
</template>

最新更新