What is the procedure for adding a function to attributes?

I need assistance looping through the array cost_classification_options to replace underscores with spaces and capitalize the first letter of each string. I created a method called convertToTitleCase(str) for this purpose, but it doesn't seem to be working correctly. How can I properly implement the convertToTitleCase(str) method in the :options component of Vue-multiselect ()?

<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>

Your assistance is greatly appreciated.

Answer №1

Eliminate the async keyword from the beginning of the function:

functions: {
        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(' ');
        },
    },

Add a calculated attribute and transform all choices using the function:

computed: {
  optionsForSelection() {
    return this.list_of_choices.map(opt => this.convertToTitleCase(opt))
  },
},

Update the structure to look like this:

<multiselect
  v-model="form.selected_choice"
  :options="optionsForSelection"
  :multiple="false"
  :taggable="false"
  :tabindex="6"
></multiselect>

Answer №2

Instead of overcomplicating the logic, you can simplify it by looping through the options array in the mounted() hook.

See It in Action :

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="691f1c0c44041c051d001a0c050c0a1d295b4759475a">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="403635256d2d352c342933252c25233400726e706e73">[email protected]</a>/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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions for making a crossword-inspired grid using a high quantity of divs or alternative elements

I am looking to create a grid on the screen of a web browser or mobile device, with each grid item containing just one letter. It's similar to a crossword puzzle, but taking up most of the screen. I've tried using divs for this purpose, but it se ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Error: Cannot access collection property of dbObject

I've been working on fetching data from a database, but I've hit a roadblock. I keep encountering an error and can't seem to figure out what's causing it. I've searched for solutions but haven't found one that works yet. I&apo ...

When making a jQuery ajax request to the Google Maps API, an error is returned stating "SyntaxError:

I'm trying to make an ajax call using jsonp to the Google Maps API v3, but it keeps ending up in the error function. In the Firefox console log, I see the following error message: SyntaxError: invalid label "results" : [ When I click on it, I can se ...

Personalize the Jquery datatables GET request parameters for the server by tailoring them to your preferences

I'm using Jquery datatables and would like to customize the GET request it sends to the server when loading a page, instead of the default GET request. Below is the JavaScript section where the request is sent on load: $(document).ready(function() { ...

An issue occurred with the session being undefined in Node.js Express4

I'm encountering an issue where my session is undefined in new layers even after setting the value within an "if" statement. /*******************************************/ /**/ var express = require('express'), /**/ cookieParse ...

Effortlessly Implementing Personalized Event Triggers using jQuery

On my website, I have a complex JavaScript module that is utilized on various pages. After some investigation and experimentation, I devised a method to execute additional code when one of the functions from the module is run on a specific page. // Within ...

A guide on incorporating a link to an external website once a Card is clicked in React JS

I have a code snippet for the Cards.js file that displays a card which links to the Services page on my website. I now want to add a link to an external website. How can I achieve this? Do I need to include an <a href= link in the Cards.js file? import ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

Insert the picture into an HTML document and retrieve the image file location

I successfully used <input type="file" accept="image/*"> to upload an image and then applied base64 encoding of the image in the onload callback function of a FileReader instance. However, I encountered a problem when trying to assign this base64 enc ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

Guide to adding new data to a JSON array

I'm currently working on implementing a punishment system using discord.js where the actions taken against users are logged by the Discord bot in a JSON file. The structure of the punishment data is as follows: { "username": "baduser# ...

Unexpected EOF error occurred when parsing JSON data using AJAX, Javascript, and Servlet in a Java application

Currently, I am encountering an obstacle with my login request. The error message displayed is as follows: [object Object] parsererror SyntaxError: JSON Parse error: Unexpected EOF Despite successfully sending the request (as confirmed by the ...

Unlocking nested JSON data in React applications

Encountering an issue while retrieving a nested JSON object from a local API endpoint /user/{id}. Here is an example of the JSON object: {"userId":122,"name":"kissa","email":"<a href="/cdn-cgi/l/email-protect ...

Edit script: Iterate through the different div elements at regular intervals AND pick a specific div by pressing a button

Check out this interesting discussion about displaying and hiding divs at specific time intervals using jQuery on the page here. The script mentioned is designed to loop through DIVs, showing one after the other while hiding the rest. It's titled "Lo ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

When attempting to access the Angular app in Edge, it automatically redirects to open in IE 11 instead

I have encountered an issue with my angular 5 App. It works perfectly fine in Chrome and Firefox, but when I try to open it in Microsoft Edge on Windows 10, the application always opens in the IE 11 browser. There are no errors displayed on the console. W ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

Identifying and troubleshooting issues in a React application operating within an nginx proxy

My React app is currently running on localhost:3000, while my Backend API is running on localhost:8181. To address cross-origin request issues and ensure compatibility, I have implemented an nginx reverse proxy setup for both the react app and backend API. ...

Can a web application determine if Microsoft Excel has been installed?

Currently, I am developing a web application using ASP.NET that includes certain functionalities which rely on Microsoft Excel being installed on the user's device. In case Excel is not available, I would prefer to deactivate these features. I am foc ...