Skip to content
Advertisement

Change the output data in a VueJS multiselect

This is a VueJS multiselect html output. It pulls the data from a JSON file via axios. I cannot change the data. I would like to be able to amend the text if possible and hide the blank entry.

So instead of ‘BL’, I would like it to display ‘Black’ and instead of ‘BLK’, I would like it to display ‘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 help appreciated?

Advertisement

Answer

Either format upon fetching or use computed properties.

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

        ...

        return color
      })
    })
  }
}

or

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

      ...

      return color
    })
  }
}

You can also create a color map and reference that instead of multiple if statements.

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

const colorName = colors['BLK']
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement