V-for =“项目中的项目”。在计算属性中使用“项目”

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

标签: vue.js

这是我的代码:

 <div v-for="list in getList" :key="list.id" class="tab">
        <h3>{{day(list)}}</h3>
        <div class="details">
            <img :src="require('../assets/day.svg')" alt="icon">
            <h4 class="description">{{list.weather[0].description}}</h4>
            <h4 class="max-temp">{{list.temp.max}}°C</h4>
            <h4 class="min-temp">{{list.temp.min}}°C</h4>
        </div>
    </div>

和我的脚本:

day(arg) {
  var timestamp = arg.dt;
  var a = new Date(timestamp * 1000);
  var days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return days[a.getDay()];
},

如何使用列表作为参数?还是有将“列表”传递给我的计算属性的方法?

3 个答案:

答案 0 :(得分:2)

计算属性不带参数,但可以使用filter

在您的组件定义中

filters: {
  weekday (timestamp) {
    let date = new Date(timestamp * 1000)
    return date.toLocaleDateString('en', {weekday: 'long'})
  }
}

并在您的模板中

<h3>{{ list.dt | weekday }}</h3>

在每个渲染周期运行方法时,最好使用过滤器而不是方法。参见https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

答案 1 :(得分:1)

您不能将参数传递给computed property。在VueJS中,computed properties源自data

如果您想要传递参数之类的东西,请使用methods而不是computed properties

如果您仍然想使用computed properties,则可以基于列表数据派生一个新列表,这样,它将具有一个新属性,即day属性。

答案 2 :(得分:0)

您可以通过匿名函数将参数传递给计算器

其他人提到您不能将参数传递给 mov rax, 0xAAAAAAAAA,但是您可以像这样轻松地做到这一点:

computed

那么你可以在你的 computed: { day() { return (list) => { // You now have access to the list argument you're trying to pass this computed } } } 中做这样的事情:

template

所有这些都说了这种将数据传递给 <div v-for="list in getList" :key="list.id"> <h3>{{day(list)}}</h3> <div class="details"> <img :src="require('../assets/day.svg')" alt="icon"> <h4 class="description">{{list.weather[0].description}}</h4> <h4 class="max-temp">{{list.temp.max}}°C</h4> <h4 class="min-temp">{{list.temp.min}}°C</h4> </div> </div> 的方式可能有它的用例,但大多数情况下,您最好使用 computed method .

相关问题