[Vuejs]-Using vue-select or another nice select box with ESM vuild of Vue 3

1👍

This is not using esm build of vue 3, but this still uses UMD build which is supported directly in the browser (the reason is because vue-select library doesn’t provide the esm build version, but it still supports UMD build).

Basically include the dependencies this way:

<script src="https://unpkg.com/vue@latest"></script>
<script src="https://unpkg.com/vue-select@beta"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css" />

Then import the vue this way:

const { createApp } = Vue;

Then import the vue-select component this way:

const app = createApp({
  components: {
    vSelect: window["vue-select"],
  },
  ...

Working code snippet:

<html>
  <head>
    <title>Test</title>
    <script src="https://unpkg.com/vue@latest"></script>
    <script src="https://unpkg.com/vue-select@beta"></script>
    <link
      rel="stylesheet"
      href="https://unpkg.com/vue-select@latest/dist/vue-select.css"
    />
  </head>
  <body>
    <div id="vuetest">
      <v-select :options="flattenedFtAssignemnts" label="text"></v-select>
    </div>

    <script type="module">
      const { createApp } = Vue;

      const app = createApp({
        components: {
          vSelect: window["vue-select"],
        },
        data() {
          return {
            ft_assignment: "a",
            ft_assignments: [
              {
                text: "hi",
                children: [
                  { id: "a", text: "a1" },
                  { id: "b", text: "b1" },
                ],
              },
              {
                text: "there",
                children: [
                  { id: "c", text: "c1" },
                  { id: "d", text: "d1" },
                ],
              },
            ],
          };
        },
        computed: {
          flattenedFtAssignemnts() {
            return this.ft_assignments.map(obj => obj.children).flat();
          }
        },
        watch: {
          ft_assignment(v) {
            console.log(v);
          },
        },
      });

      app.mount("#vuetest");
    </script>
  </body>
</html>

Unfortunately vue-select currently doesn’t support <optgroup>, so I had to flatten the children for select.

0👍

If you don’t want to use plugins and prefer to build it on your own (I like to do it this way).

To do this, you can created a div containing an input type text, which you can use to search for the options inside the div. The options are stored as anchor tags within a hidden div. Then, attaching an event listener to the anchor tag elements with the function they need to call.

Check this out, you can of course edit it and make it work the way you need it.

Leave a comment