我有一个数据集,要在其上迭代以显示v-data-table
中的某些字段。我如何做到这一点,以便如果图标字段的值为G
,则会出现某个图标。如果它有F
,将出现一个不同的图标,如果它有GF
,则两个图标将出现在同一行。
这里是一个示例pen。
new Vue({
el: '#app',
data() {
return {
headers: [{
text: 'Dessert (100g serving)',
align: 'left',
sortable: false,
value: 'name'
},
{
text: 'Calories',
value: 'calories'
},
{
text: 'Fat (g)',
value: 'fat'
},
{
text: 'Icon Field',
value: 'icon'
}
],
desserts: [{
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
icon: 'GF'
},
{
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
icon: 'F'
},
{
name: 'Eclair',
calories: 262,
fat: 16.0,
icon: 'G'
},
{
name: 'Cupcake',
calories: 305,
fat: 3.7,
icon: 'GF'
},
]
}
}
})
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<v-app id="inspire">
<v-data-table :headers="headers" :items="desserts">
<template v-slot:items="props">
<td>{{ props.item.name }}</td>
<td>{{ props.item.calories }}</td>
<td>{{ props.item.fat }}</td>
<td> {{ props.item.icon}} </td>
</template>
</v-data-table>
</v-app>
</div>
我尝试设置v-if = props.item.icon == 'GF'
,但这似乎不起作用。任何帮助将不胜感激。谢谢。
答案 0 :(得分:2)
您不得在v-for中使用v-if。您可以过滤数组,然后进行迭代。
有指向Vue最佳做法的有用链接 https://vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential
答案 1 :(得分:1)
一种方法是添加要渲染的图标列表,然后使用v-for
// data
icons: {
F: ["gavel"],
G: ["event"],
GF: ["gavel", "event"]
},
// template
<td>
<v-icon v-for="icon in icons[props.item.icon]">{{icon}}</v-icon>
</td>
这样,您便拥有了不错的可扩展解决方案:-)
答案 2 :(得分:0)
使用Vue过滤器,有关更多信息,请从此处阅读 https://vuejs.org/v2/guide/filters.html
...
filters: {
getIcon(value) {
if (value == "G") {
return "your icon"
}
else if (value == "GF") {
return "your icon"
}
else if (value == "F") {
return "your icon"
}
}
}
...
...
<td> {{ props.item.icon | getIcon}} </td>
...
答案 3 :(得分:0)
我不使用Vue编写代码,但是类似的东西应该可以工作,您可以使用图标数组并使用“ icons.map(icon => <>)”等。
让甜点= [
{
name: 'ice',
icon: 'G'
},
{
name: 'ice2',
icon: 'E'
},
{
name: 'ice3',
icon: 'F'
}
]
让图标= {
val1: '',
val2: '',
val3: ''
};
desserts.forEach((dessert)=> {
switch(dessert.icon){
case 'G':
icons.val1 = 'http://iconurl'
case 'E':
icons.val2 = 'http://iconurl'
case 'F':
icons.val3 = 'http://iconurl'
}
})