概要
Vueでセレクトボックスのライブラリを探すと、Vue-multiselectの記事がけっこう出てくるのですが、[Vue3]Vue-multiselect を用いた、ドロップダウンの実装とサンプルアプリの記事にある通り、Vue3への対応が怪しい感じがするとのこと。2022年1月時点ではVue3対応のリポジトリはあるものの、あまり更新されていませんでした。
ので今回は、上記の記事で紹介されていたvueform/multiselectというライブラリを使用して、Vue3でタグ選択を実装してみたので紹介したいと思います。
実装方法
こちらのドキュメントにコンポーネントに設定できるpropsが記載されています。
mode
という項目が、入力の種別(single|multiple|tags
)を設定する箇所になります。tag 選択を実装するには、tagsを指定すればOKです。念のため、該当箇所のキャプチャーを以下に添付します。
実装サンプル
実装サンプルは以下です。optionには、選択できるカテゴリーの一覧を設定する想定としています。
なお、vee-validateを今回併せて使用したのでサンプルにも含めていますが、特に使用する必要はないです。
<template>
<Multiselect
v-model="categoriesValue"
:options="categoryOptions"
mode="tags"
placeholder="カテゴリー選択"
/>
</template>
<script>
import { defineComponent, getCurrentInstance } from "vue";
import { useField } from "vee-validate";
import Multiselect from "@vueform/multiselect";
export default defineComponent({
props: ["categories"],
components: {
Multiselect,
},
setup() {
const app = getCurrentInstance();
const props = app.props;
// カテゴリーの選択一覧
const categoryOptions = props.categories.map((c) => {
return {
label: c.name,
value: c.id,
};
});
// カテゴリーの入力フィールド
const { value: categories } = useField("categories");
const categoriesValue = computed({
get: () => categories.value,
set: (value) => {
categories.value = value;
},
});
return {
categoryOptions,
categoriesValue,
};
},
});
</script>
<style src="@vueform/multiselect/themes/default.css"></style>