Home > Blockchain >  Change the output data in a VueJS multiselect
Change the output data in a VueJS multiselect

Time:10-04

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  tabindex="-1">
    <ul >
      <li ><span>BL</span></li>
      <li ><span></span></li>
      <li ><span>BLK</span></li>
      <li ><span>GR</span></li>
      <li ><span>PUR</span></li>
      <li ><span>YEL</span></li>     
    </ul>

Any help appreciated?

CodePudding user response:

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

CodePudding user response:

Try to create Map of your options and then filter and map your values:

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/[email protected]"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/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>

  • Related