Modify the output information in a VueJS dropdown menu

I have a VueJS multiselect component that is displaying data from a JSON file using axios. Unfortunately, I am unable to modify the data directly. However, I would like to edit the text displayed and hide any blank entries.

For example, I want 'BL' to be shown as 'Black', 'BLK' as 'Blue', etc.

<div class="multiselect-dropdown is-hidden" tabindex="-1">
    <ul class="multiselect-options">
      <li class="multiselect-option"><span>BL</span></li>
      <li class="multiselect-option"><span></span></li>
      <li class="multiselect-option"><span>BLK</span></li>
      <li class="multiselect-option"><span>GR</span></li>
      <li class="multiselect-option"><span>PUR</span></li>
      <li class="multiselect-option"><span>YEL</span></li>     
    </ul>

Any assistance with this issue would be greatly appreciated!

Answer №1

To enhance efficiency, consider implementing either format modification during data retrieval or utilize computed properties.

methods: {
  getColors() {
    api.get().then((colors) => {
      this.colors = colors.map((color) =>
        if (color.name === 'BLK') {
          color.name = 'Black'
        }

        ...

        return color
      })
    })
  }
}

Alternatively,

computed: {
  colorsForMultiselect() {
    return this.colors.map((color) =>
      if (color.name === 'BLK') {
        color.name = 'Black'
      }

      ...

      return color
    })
  }
}

You may also simplify the code by creating a color mapping system instead of utilizing multiple conditional statements.

const colors = {
  'BLK': 'Black',
}

const colorName = colors['BLK']

Answer №2

Utilize the Map feature to organize your choices and then apply filters and mappings to your data:

new Vue({
  el: '#app',
  components: { Multiselect: window.VueMultiselect.default },
  data () {
    return {
      value: [],
      options: [{name:'BL'}, {name: ''}, {name: 'BLK'}, {name: 'GR'}, {name: 'PUR'}, {name: 'YEL'}],
      mapOptions: new Map([['bl', 'Blue'], ['blk', 'Black'], ['gr', "Green"], ['pur', 'Purple'], ['yel', 'Yellow'])
    }
  },
  computed: {
    filteredOptions() {
      return this.options
        .filter(o => o.name)
        .map(m => {
          m.desc = this.mapOptions.get(m.name.toLowerCase())
          return m
        })
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="205655450d4d554c544953454c45435460120e110e10">[email protected]</a>"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4c2c1d199d9c1d8c0ddc7d1d8d1d7c0f4869a859a84">[email protected]</a>/dist/vue-multiselect.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<div id="app">
  <multiselect
    v-model="value"
    placeholder="name"
    label="desc" track-by="name"
    :options="filteredOptions"
    :multiple="true"
    :taggable="true"
  ></multiselect>
  {{value}}
</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

Why does the <select> dropdown flash when I select it?

Currently utilizing Angular 1.3 and Bootstrap 3.3.x CSS without the JS functionality. There is also an interesting animated GIF embedded within. <div class="form-group"> <div class="col-lg-3"> <label clas ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

Discover Headphones with Ionic

Is there a way to detect if headphones are connected to a mobile device (specifically an iPhone) using Ionic? Our Ionic app plays sound normally without headphones, but encounters issues when headphones are plugged in. When you start the app without headp ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Retrieving data from various endpoints using React JS

Here is the code snippet to fetch contents from my Django server: However, I also need to fetch from another URL: I am unsure how to achieve this. Any assistance would be greatly appreciated. useEffect(() => { fetch("http://127.0.0.1:8000/api/con ...

Difficulty encountered when transferring an array from Xcode to JavaScript via SBJSON

In an attempt to transfer an array from Xcode to a local HTML file, I am utilizing jQuery in the HTML code. This involves using loadHTMLString: with baseURL to read both the HTML and included .js files. However, I am encountering an issue when trying to us ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...

Is there a replacement for jQuery's each() function in vanilla JavaScript?

When working with jQuery, we often use the each function in our code like the example below: $('button').each(function(i) { $('button').eq(i).css('background', 'red'); }); Is there a way to achieve similar functi ...

Leveraging AJAX to call upon a designated php file

I have a selection of menu items on my webpage, each with different options: option1, option2, and option3. Additionally, I have corresponding PHP files on my server for each of these menu items: option1.php, option2.php, and option3.php. For simplicity, ...

Issue with adding HTML content to bootstrap modal not functioning as expected

Having trouble displaying an image in a bootstrap modal by using data- attribute within a php foreach loop. The image doesn't seem to appear in the target div. Here's my code snippet: <script> $(document).ready(function(){ $( ".subscri ...

Utilizing external sources to add texture to 3D models in WebGL

After mastering the art of applying texture to my 3D-models in WebGL using .mtl files (and .obj files), the process works seamlessly when the images are saved on my local computer. Below is an excerpt from my .mtl file showcasing how the texture is applied ...

Transforming .POST into corresponding .AJAX techniques

I'm currently attempting to convert a .post javascript call into an equivalent .ajax call in order to make it asynchronous. However, I'm running into some issues and can't seem to get it to work. The original working .post call looks like th ...

Reveal the administrator's details exclusively when the associated radio button is chosen

Managing administrators for a post can be done through an editing page with corresponding radio buttons. Each radio button is linked to a different administrator, and selecting one populates the form fields with that admin's details. The issue arises ...

Code snippet for positioning a div element above a canvas when clicked on the canvas

Currently, I am working on connecting an HTML5 canvas element with an event listener for clicks to a floating div that will appear exactly where the user clicks on the canvas. Can anyone provide any suggestions or code snippets for the best way to achieve ...

Looking to efficiently output information generated within a headless browser in node.js

Is there a way to print out data created inside a Node.js running headless browser if console.log('Text') isn't working? For example: const pup = require('puppeteer'); const chrom = await pup.launch({headless:'new'}); ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

Executing a VueJS getter function in the browser console - a step-by-step guide

I'm trying to debug a VueJS component and I want to test the behavior of a getter in the browser. Can I manually call it from the browser console? Update: This link provides information on how to trigger a state change manually. In particular: You ...