【发布时间】:2018-11-05 00:15:14
【问题描述】:
请告诉我是否可以为v-select 自定义item-text ?
我想自定义v-select 中的每个项目,如下所示:
:item-text="item.name - item.description"
【问题讨论】:
标签: javascript vue.js vuetify.js
请告诉我是否可以为v-select 自定义item-text ?
我想自定义v-select 中的每个项目,如下所示:
:item-text="item.name - item.description"
【问题讨论】:
标签: javascript vue.js vuetify.js
下面是一个简单的代码示例:
<template>
<v-select
label="Names"
v-model="name"
:items="names"
item-value="id"
item-text="name"
return-object
>
<template v-slot:selection="{ item }">
{{ getText(item) }}
</template>
<template v-slot:item="{ item }">
{{ getText(item) }}
</template>
</v-select>
</template>
<script>
export default {
data: () => ({
names: [
{ id: 1, name: 'Paul', age: 23 },
{ id: 2, name: 'Marcelo', age: 15 },
{ id: 3, name: 'Any', age: 30 },
],
name: null,
}),
methods: {
getText(item) => `${item.name} - ${item.text}`,
},
}
</script>
以下为参考: https://vuetifyjs.com/en/components/autocompletes#advanced-slots
【讨论】:
如果您不想处理插槽或其他方法来操作项目文本。这是实现相同结果的另一种不同方法。
只需使用计算方法动态添加一个新的 'displayname' key: value 对到您的 v-model 集合,并将其用作 select 的 v-model 并将新键用作 item-text
computed: {
addDisplayname() {
return names.map(v => ({ ...v,
displayname: v.name + ' - ' + v.description
}))
}
}
【讨论】:
是的,您可以按照文档中的说明使用scoped slot 并提供template。
对于v-select,你有两个scoped slot:
selection :描述v-select 在选中时应如何呈现项目item :描述v-select 在打开时应该如何呈现项目看起来像这样:
<v-select> // Don't forget your props
<template slot="selection" slot-scope="data">
<!-- HTML that describe how select should render selected items -->
{{ data.item.name }} - {{ data.item.description }}
</template>
<template slot="item" slot-scope="data">
<!-- HTML that describe how select should render items when the select is open -->
{{ data.item.name }} - {{ data.item.description }}
</template>
</v-select>
CodePen with a complex example
Vuetify Doc about Scoped Slot in V-Select
为 Vuetify 1.1.0+ 编辑:这些插槽也可用于新组件 v-autocomplete 和 v-combobox,因为它们继承自 v-select。
为 Vue 2.6+ 编辑,替换:
slot="selection" slot-scope="data"v-slot:selection="data"
slot="item" slot-scope="data"v-slot:item="data"
【讨论】:
template 标记必须同时具有 slot 和 slot-scope 属性。这对我来说并不明显。
<template v-slot:item="data">
速记:
:item-text="item => item.name +' - '+ item.description"
【讨论】:
:item-text="item =>`${item.name} - ${item.description}`"
filter props,它接受一个带有itemText的函数
Slot 移除焦点时的自动选择。
item-text 可以是:string | array | function
那么我们可以制作:
:item-text="text"
和
methods: {
text: item => item.name + ' — ' + item.description
}
【讨论】:
.join(',') 别名。 Just try
:item-value也可以用来设置选中的值。