Home » vue » How to use function computed to display variable in vue template + laravel

How to use function computed to display variable in vue template + laravel

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want to display the variable from the database and round it before. Can you help me about syntax for this.

<h2 class="txt-bold">Rating: {{roundHalf(ListOrg.rating)}}</h2>


computed: {
    roundHalf: function(num) {
      return Math.round(num * 2) / 2;
    }
  }
Answers:

If you want to use computed value :

<h2 class="txt-bold">Rating: {{roundHalf}}</h2>


computed: {
    roundHalf: function() {
      return Math.round(this.ListOrg.rating * 2) / 2;
    }
  }

###

Better to use Vue filter :

Define a filter : (Global filter)

Vue.filter('roundHalf', function (value) {
    return Math.round(value * 2) / 2;
})

And use in vue file like :

<h2 class="txt-bold">Rating: {{ListOrg.rating | roundHalf}}</h2>

Defining a global filter will help you use it everywhere in the project. 🙂

Reference :
Vue Filter