Vue3 ライブラリ「vue3-treeselect」を使用してツリー状で選択可能なセレクトボックスを実装する

Vue3 ライブラリ「vue3-treeselect」を使用してツリー状で選択可能なセレクトボックスを実装する

ライブラリ「vue3-treeselect」を使用して、ツリー状で選択可能なセレクトボックスを実装することが可能です。ここでは、「vue3-treeselect」を利用するための手順と簡単な使い方を記述してます。

環境

  • OS  windows10 64bit
  • vue 3.0.0
  • node v14.17.0
  • yarn 1.22.10
  • @vue/cli 4.5.9

Vue3環境構築

vue-cliを使用して構築してます。

## @vue/cliインストール
npm install -g @vue/cli

## 初期化
npm init

## upgrade
vue upgrade --next

## vueappというプロジェクトを作成
vue create vueapp

## vue 3を選択
Vue CLI v4.5.13
? Please pick a preset:
  Default ([Vue 2] babel, eslint)
> Default (Vue 3) ([Vue 3] babel, eslint) 
  Manually select features

## 移動
cd vueapp

vue3-treeselectインストール

yarnを使用して、インストールします。

yarn add vue3-treeselect

yarnがインストールされていない場合は、以下のコマンドでインストール可能です。

npm install -g yarn

vue3-treeselect使い方

src配下のApp.vueを下記のように編集します。

<template>
  <div>
    <treeselect v-model="value" :multiple="true" :options="options" />
  </div>
</template>

<script>
import Treeselect from "vue3-treeselect";
import "vue3-treeselect/dist/vue3-treeselect.css";

export default {
  name: "App",
  components: {
    Treeselect,
  },
  data() {
    return {
      // define the default value
      value: null,
      // define options
      options: [
        {
          id: "a",
          label: "a",
          children: [
            {
              id: "aa",
              label: "aa",
            },
            {
              id: "ab",
              label: "ab",
            },
          ],
        },
        {
          id: "b",
          label: "b",
        },
        {
          id: "c",
          label: "c",
        },
      ],
    };
  },
};
</script>

<style>
#app {
  margin: 0 auto;
  margin-top: 300px;
  min-height: 100vh;
  width: 500px;
  justify-content: center;
  align-items: center;
  text-align: center;
}
</style>

起動

起動します。

yarn serve

ブラウザから http://プライベートIP or localhost:8080にアクセスすると、ツリー状で選択可能なセレクトボックスが実装されていることが確認できます。