I'm trying to loop through the cost_classification_options
array and replace underscores with spaces, at the same time, capitalize the first letter of each string. I've done a method convertToTitleCase(str)
, to do this, but doesn't seem to work. How can I insert convertToTitleCase(str) method correctly in :options
(https://vue-multiselect.js.org/)?
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
<script>
import Form from 'vform'
import Multiselect from 'vue-multiselect'
export default {
components: {
Multiselect
},
data: () => ({
errors: {},
form: new Form({
designation_id: [],
position_id: [],
cost_classification: []
}),
designation_options: [],
position_options: [],
cost_classification_options: ['direct_labor', 'indirect_labor', 'general_and_admin']
}),
methods: {
async convertToTitleCase(str) {
const arr = str.split('_');
const result = [];
for (const word of arr) {
result.push(word.charAt(0).toUpperCase() word.slice(1).toLowerCase());
}
return result.join(' ');
},
},
created: function() {
this.getDesignationNames();
this.getPositionNames();
},
}
</script>
<multiselect
v-model="form.cost_classification"
:options="cost_classification_options"
:multiple="false"
:taggable="false"
:tabindex="6"
></multiselect>
Any help is much appreciated.
CodePudding user response:
Remove the async
keyword from the first of the method:
methods: {
convertToTitleCase(str) {
const arr = str.split('_');
const result = [];
for (const word of arr) {
result.push(word.charAt(0).toUpperCase() word.slice(1).toLowerCase());
}
return result.join(' ');
},
},
Create a computed
property and convert all of options with the method:
computed: {
selectOptions() {
return this.cost_classification_options.map(opt => this.convertToTitleCase(opt))
},
},
Change the template to this:
<multiselect
v-model="form.cost_classification"
:options="selectOptions"
:multiple="false"
:taggable="false"
:tabindex="6"
></multiselect>
CodePudding user response:
Instead of making the logic complex. You can simply achieve it by iterating the options array in the mounted()
hook.
Working Demo :
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data: {
cost_classification: [],
cost_classification_options: ['direct_labor', 'indirect_labor', 'general_and_admin']
},
mounted() {
this.cost_classification_options = this.cost_classification_options.map(opt => {
const arr = opt.split('_');
let str = '';
for (const word of arr) {
str = word.charAt(0).toUpperCase() word.slice(1).toLowerCase() ' ';
}
return str.trim();
})
}
}).$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-multiselect.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vue-multiselect.min.css"/>
<div id="app">
<multiselect
v-model="cost_classification"
:options="cost_classification_options"
:multiple="false"
>
</multiselect>
<pre>{{ cost_classification }}</pre>
</div>