在Vue Js for循环中动态调用函数

时间:2018-07-04 10:01:49

标签: jquery html vue.js

我有一个保存在Vue数据中的json,如下所示:

new Vue({
    el: 'myDiv',
    data: {
            dishes: Dishes
          }
       })

我的Json如下:

Dishes = [
            {
                Id: 1,
                Name: "First dish",
                Rating: 2.5
            },
            {   
                Id: 2,
                Name: "Second dish",
                Rating: 1.5
            },
            {
                Id: 1,
                Name: "Third dish",
                Rating: 4.5
            }
        ]

我在DOM中使用的代码如下所示:

<ol id="myDiv">
   <li v-for="dish in dishes">
      {{dish.Name}}
    //call a function to adjust ratings and get the generated html, 
    //eg:call function ratingAdjustor(dish.Rating);
  <li>
</ol>

我的功能等级调节器如下所示:

function 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
    }
}

由于“ v-for”中存在数据处理问题,我不知道如何进行操作,我想从v-for中获取评分值,调用一个函数以获取最接近的值并创建带有星号的html元素并返回包含html的字符串。 但是我不知道该怎么做。 “ v-on”仅在发生任何事件时才有用,例如:“ v-on:click =“ someFunctionName””,因为这应该在运行循环而不发生事件时发生,这变得棘手。

2 个答案:

答案 0 :(得分:1)

将函数放入视图模型的methods部分:

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
    }
  }
}

然后,您可以像使用普通数据属性一样使用该方法(您可以通过参数):

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

请不要在条件块内创建变量。同样,您的函数在else情况下返回undefined。解决这个问题。

答案 1 :(得分:1)

您可以尝试以下代码

 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>