computed property parameter argument issue Hey guys
I'm trying to use computed property to convert a number in a currency format
I have this mark up below :
<h4 class="box-title"> {{billed_total_ht}}€</h4>
I called here a computed property
<h4 class="box-title"> {{ convert_currency(billed_total_ht) }}€</h4>
then
computed: {
convert_currency(price)
{
return price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67
}
}
I'm getting an error
[Vue warn]: Error in render: "TypeError: price.toFixed is not a function"
what's causing that?
@atef95 I don't think you can pass arguments to computed properties like that. Instead, try a method:
methods: {
convert_currency(price)
{
return price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67
}
}
If you are always using basing the convert_currency on the billed_total_ht then you could use it in the computed property.
computed: {
convert_currency()
{
return this.billed_total_ht.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67
}
}
@rhymesey yes it's working but wanted to declare one function that accepts different arguments..
it seems methods are more adequate in this situation
@atef95 One of the main benefits of computed properties are they are cached. They only re-evaluate if the reactive dependencies change. This makes computed properties a great tool for somewhere to place complex logic that can be called multiple times.
If you're passing parameters, where the parameter is different each time, then a method is certainly the better way to go.
If this has solved your problem, please close out the thread by selecting best answer.
You could also use a filter in Vue which might be more reusable. You can declare it on the component or globally.
Vue.filter('convert_currency', function (value) {
return value.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
})
new Vue({
// ...
})
Then in your component
<h4 class="box-title"> {{ billed_total_ht | convert_currency }}€ </h
Please sign in or create an account to participate in this conversation.