[Vuejs]-Calling a function dynamically in Vue Js for loop

1๐Ÿ‘

โœ…

Put your function in the methods section of your viewmodel:

methods: {
  ratingAdjustor(rating) {
    if (rating % 1 != 1){
      //round to the nearest value
      //maybe nearst value is 3
      var stars = ""; 
      for(i=0; i< roundedRaating; i++){
        stars += '<span>//Star SVG icons highlighted</span>'; 
        // hence 3 highlighted stars
        }
        //rest of the non highlighted stars
      return stars; // which has stars based on ratings
    }
  }
}

You can then use the method like a normal data property (which you pass a parameter):

<ol id="myDiv">
   <li v-for="dish in dishes">
      Name of the dish:{{dish.Name}} 
      <br />
      Rating: {{ ratingAdjustor(dish.Rating) }}
   <li>
</ol>

Please not that you should create variables inside conditional blocks. Also, your function returns undefined in the else case. Fix that.

๐Ÿ‘คconnexo

1๐Ÿ‘

you can try the following code

 import Dishes from './file.json';
    export default{
        data(){
            return{
                 dishes: Dishes
            }
        },
       
    }
//CREATE file.json
[
    {
        "Id": 1,
        "Name": "First dish",
        "Rating": 2.5
    },
    {   
        "Id": 2,
        "Name": "Second dish",
        "Rating": 1.5
    },
    {
        "Id": 1,
        "Name": "Third dish",
        "Rating": 4.5
    }
]

//show.vue
<ul>
                <li v-for="item in dishes">
                    {{item.Name}}
                </li>
            </ul>
๐Ÿ‘คskipperhoa

Leave a comment