Create a searchable select field with InertiaJS and vue multiselect

Constantin Druc ยท 17 Feb, 2021
  1. Install vue-multiselect
1npm install vue-multiselect --save
  1. Import and register the Multiselect component
1import Multiselect from 'vue-multiselect';
2 
3export default {
4 components: {Multiselect}
5}
  1. Import the styles in your app.css file
1@import "../../node_modules/vue-multiselect/dist/vue-multiselect.min.css";
  1. Prepare your InertiaJS form
1export default {
2 data() {
3 return {
4 form: this.$inertia.form({
5 mechanic_id: '',
6 // other fields
7 })
8 }
9 }
10}
  1. Add the multiselect directive in your template and setup it's options, property to be used as label, an unique property for track-by to identify each option, and listen to the @search-change and @input events.
1<template>
2 <form>
3 <label for="mechanic_id">Mechanic</label>
4 <multiselect
5 v-model="selectedMechanic"
6 id="mechanic_id" placeholder="Search mechanic"
7 :options="mechanics" label="name" track-by="id"
8 @search-change="onSearchMechanicsChange"
9 @input="onSelectedMechanic"
10 />
11 </form>
12</template>
  1. Define the above properties and methods. mechanics will come from the server, so it will be defined as a prop with an empty array as default, while onSearchMechanicsChange and onSelectedMechanic will defined as methods.
1export default {
2 props: {
3 mechanics: {
4 type: Array,
5 default: () => []
6 }
7 },
8 data() {
9 return {
10 selectedMechanic: undefined,
11 form: this.$inertia.form({
12 mechanic_id: '',
13 // other fields
14 })
15 }
16 },
17 methods: {
18 onSearchMechanicsChange(term) {
19 this.$inertia.get('/jobs/create', {term}, {
20 preserveState: true,
21 preserveScroll: true,
22 replace: true
23 })
24 },
25 onSelectedMechanic(consultant) {
26 this.form.consultant_id = consultant.id;
27 },
28 }
29}

The reason why we set the multiselect v-model to selectedMechanic and not form.mechanic_id is because the multiselect component expects its v-model to be an element from the mechanics array we pass in as options.

The onSearchMechanicsChange will make an inertia call to the server while passing the entered term in the search field. We also need to make sure the local state and scroll will stay the same, so we'll instruct inertia to preserveState and preserveScroll.

Since the search request will fire multiple times, we also want to replace the current request in the browser history such that when we browse back, we browse to the previous page, and not to the previous term that was typed in the search box.

Lastly, the onSelectedMechanic will set the form.consultant_id to the id of the selected mechanic.