InertiaJS & Laravel misc
Create a searchable select field with InertiaJS and vue multiselect
13:10- Install vue-multiselect
npm install vue-multiselect --save
- Import and register the
Multiselect
component
import Multiselect from 'vue-multiselect';
export default {
components: {Multiselect}
}
- Import the styles in your
app.css
file
@import "../../node_modules/vue-multiselect/dist/vue-multiselect.min.css";
- Prepare your InertiaJS form
export default {
data() {
return {
form: this.$inertia.form({
mechanic_id: '',
// other fields
})
}
}
}
- Add the multiselect directive in your template and setup it's
options
, property to be used aslabel
, an unique property fortrack-by
to identify each option, and listen to the@search-change
and@input
events.
<template>
<form>
<label for="mechanic_id">Mechanic</label>
<multiselect
v-model="selectedMechanic"
id="mechanic_id" placeholder="Search mechanic"
:options="mechanics" label="name" track-by="id"
@search-change="onSearchMechanicsChange"
@input="onSelectedMechanic"
/>
</form>
</template>
- 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, whileonSearchMechanicsChange
andonSelectedMechanic
will defined as methods.
export default {
props: {
mechanics: {
type: Array,
default: () => []
}
},
data() {
return {
selectedMechanic: undefined,
form: this.$inertia.form({
mechanic_id: '',
// other fields
})
}
},
methods: {
onSearchMechanicsChange(term) {
this.$inertia.get('/jobs/create', {term}, {
preserveState: true,
preserveScroll: true,
replace: true
})
},
onSelectedMechanic(consultant) {
this.form.consultant_id = consultant.id;
},
}
}
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
.