実務で使うことがあったので自分用でメモ。
選択肢に画像付きで表示させる
index.js
<template>
<div>
<label class="typo__label">Custom option template</label>
<multiselect
v-model="value"
placeholder="選択してください"
label="title"
track-by="title"
:options="options"
:custom-label="customLabel"
:show-labels="false"
:searchable="false"
:allowEmpty="false"
>
<template slot="singleLabel" slot-scope="props">
<img class="option__image" :src="props.option.img" alt="props.option.img">
<span class="option__title">{{ props.option.title }}</span>
</template>
<template slot="option" slot-scope="props">
<img class="option__image" :src="props.option.img" alt="props.option.img">
<span class="option__title">{{ props.option.title }}</span>
</template>
</multiselect>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
components: {
Multiselect
},
data () {
return {
value: { title: '', img: '' },
options: [
{ title: 'ooo', img: 'XXX.png' },
{ title: 'ooo', img: 'XXX.png' },
{ title: 'oooo', img: 'XXX.png' },
]
}
},
methods: {
customLabel ({ title }) {
return `${title}`
}
}
}
</script>
オプション設定
-
:options="options"
選択肢の中身を指定 -
:searchable="false"
検索機能を使わない -
:allowEmpty="false"
1つを必ず選択するようにする -
:custom-label="customLabel"
選択肢内で表示する文字をカスタム
その他
今回はVue2で書きましたが、Vue3にも対応してるっぽい事書いてあって試してみたけど上手く動きませんでした。
個人的にはスタイルも変えられる設定があったらいいな〜と思いました。
公式ドキュメントには他にもカスタムできる設定が書いてあるのでぜひ見てみてください。