Benjamin Vbg
Benjamin Vbg

Reputation: 99

Render number with nuxtjs

Need to do:

I would like to make something like this:

1
10
100
1 000
10 000
100 000
...


Example (my code):

<div class="boxe-chiffre" v-if="pops.Population"><span>Population</span> {{pops.Population}}</div>

{{pops.Population}} is number and render like this : 96629€ and i would like 96 629€


but i don't understand how to make that with nuxtjs
(just format number)

Thanks !

Upvotes: 1

Views: 3902

Answers (2)

Ali
Ali

Reputation: 1568

Your answer is inside vue custom filters documents You can add filter only to your component or you can define it globaly (reusable)

Make js file inside plugins folders and add it inside your plugins inside nuxt.config.js file. import Vue from 'vue' then use Vue.filter() function to define your custom filter

import Vue from 'vue'
Vue.filter('currency', function (value) {
  // tanks @li-x for his simple formating function
  return value.toLocaleString('en-UK', { style: 'currency', currency: 'EUR' })
  // you can add something like .replace(/,/g, ' ') after toLocaleString method to customize your formatted number
})

Then simply use it with | operator in mustache like:

<div class="boxe-chiffre" v-if="pops.Population"><span>Population</span> {{pops.Population | currency}}</div>

Also you can pass some arguments to your filter function as desçibed in documents

Upvotes: 4

li x
li x

Reputation: 4061

This isn't specifically a nuxtJS problem, it's just a rudimentary JavaScript problem that can be solved using the toLocaleString method of numbers in JavaScript.

methods: {
  toCurrencyString(number){
    return number.toLocaleString('en-UK', { style: 'currency', currency: 'EUR' })
  }
}

The following method can be used to convert a number to its currency equivalent using just vanilla JavaScript.

You could try and split and splice spaces and the currency symbol into place for a multiple of different scenarios which might work for you in the short term, but it's not a lasting solution obviously. I started writing one out only to realize that it's a complete rabbit hole, you could also look at using a JS library such as accounting.js which might be more suitable.

Here's a js fiddle showing how to implement the component: https://jsfiddle.net/eywraw8t/177932/

Upvotes: 0

Related Questions