vue中为computed计算属性传参遇到的问题,已解决

首先介绍下项目背景,

需要将 dataList 中的 item.stars 属性传入 computed 返回要展示的值

部分代码如下(请不要纠结为什么这么做,数据格式确认如此):

      <li class="recommend-list-item border-bottom"
          v-for="item of recommendList"
          :key="item.id"
      >
         <div class="recommend-list-item-comments">
            <span>{{stars(item.star)}}星</span>
          </div>
      </li>
export default {
  name: 'HomeRecommend',
  data () {
    return {
      recommendList: [
        {
          id: '0001',
          imgUrl: '/static/imgs/list/adca619faaab0898245dc4ec482b5722.jpg_250x250_0fc722c0.jpg',
          title: '故宫',
          star: [1, 1, 1, 1, 1],
          comments: '32879',
          price: '¥60',
          location: '东城区',
          desc: '世界五大宫之首,穿越与您近在咫尺'
        }
]
   }
},
computed: {
stars: function (star) {
var count = 0
star.forEach((item, index) => {
    if (item) {
count++
}
})
return count
}
}
}
}

看起来完美,npm run start ,页面一刷,报错了!

看见度娘有类似问题~点进去一看,需要闭包

修改后代码如下:

  computed: {
    stars: function () {
      return function (star) {
        var count = 0
        star.forEach((item, index) => {
          if (item) {
            count++
          }
        })
        return count
      }
    }
  }

再刷新一下,OK啦~

原文地址:https://www.cnblogs.com/zhuxingqing/p/11187596.html