When using selectboxes in Vue.js you often need to pre-select an option when presenting an edit form for example.
<label><h5 class="mt-3 ml-2">Category</h5></label> <select class="form-control mt-1" v-model="selected" @change=checkCategory> <option v-for="(category, index) in categories" :value="category.id" :selected="category.id === current_category.id"> {{category.category_name}} </option> </select>
The script then sets the original value on the mounted life-cycle hook.
<script> export default { name: "CategorySelect", props: ['categories', 'tool', 'current_category'], data() { return { show_expiry: false, selected: this.current_category.id, expiry_date: this.tool.expiry_date, category_id: this.tool.category_id, tool_name: this.tool.tool_name, tool_description: this.tool.tool_description, tool_serial: this.tool.tool_serial, tool_id: this.tool.id } }, mounted() { this.selected === this.current_category.id; if(this.current_category.needs_calibration) { if(this.expiry_date != null) { this.expiry_date = this.expiry_date.substring(0,10); } this.show_expiry = true; } }, methods: { checkCategory() { axios.get('/tool_categories/check/'+this.selected) .then((response) => { // handle success this.expires = response.data.needs_calibration; if(this.expires) { this.show_expiry = true; } else { this.show_expiry = false; } }) .catch(e => { this.errors.push(e); }); }, submitTool() { console.log("OK"); this.errors = []; axios.patch('/tools/'+this.tool_id, { tool_name: this.tool_name, tool_description: this.tool_description, category_id: this.selected, expiry_date: this.expiry_date, tool_serial: this.tool_serial }) .then((response) => { return window.location.href = '/tools'; }) .catch(e => { if(e){ console.log("Errors: "+ e) } }); } }, } </script> <style scoped> </style>
Comments