Search code examples
vue.jsvuejs2javascript-objects

proper way to display and filter an object in VueJS


Right now I have data being returned from an API that is structured like the following

{_ids: "690506", _addresses: "987394", _bids: "709395", _sids: "384130"}

<ul>
    {{Intl.NumberFormat("en-US").format(DataCounts._ids)}}
     Location Records
</ul>
<ul>
  <v-icon>{{ mdiArch }}</v-icon>
    {{Intl.NumberFormat("en-US").format(DataCounts._addresses)}}
     Location Records
</ul>
<ul>
  <v-icon>{{ mdiArch }}</v-icon>
    {{Intl.NumberFormat("en-US").format(DataCounts._bids)}}
     Location Records
</ul>

etc.....

Is there a more compartmentalized way to structure this in the UI so when/if the API changes I do not have to go and check 30 lines of code to make sure it works.


Solution

  • you can use vue filters

    https://v2.vuejs.org/v2/guide/filters.html

    // create global filter
    const mySpecialFormat = Intl.NumberFormat("en-US");
    Vue.filter('numberFormatEn', function (value) {
      if (!value) return ''
      return mySpecialFormat.format(value.toString())
    })
    
    // then use it somewhere
    {{ DataCounts._ids | numberFormatEn }}
    

    or something along those lines


    EDIT: Or did you mean how to simplify Object(k,v) -> html(ul)

    in that case something like

    https://v2.vuejs.org/v2/guide/list.html

    <ul v-for="(value,key) in DataCounts" :key="some-key">
      <v-icon v-if="...">{{ mdiArch }}</v-icon>
      {{ value | numberFormatEn }}
      Location Records
    </ul>