我正在学习 vujs,并陷入了我自己的过滤器和日期比较示例中。 我在第二行中有两个相似的字符串(如日期“2020-02-02”),我应该看到“今天”一词,但它不起作用。
为什么在模板中的
typeof
上,带有过滤器的日期是数字?比较这些日期我做错了什么?它总是
false
。
您可以在此处看到代码或 https://jsfiddle.net/2awtdny4/9/
html:
<div id="app">
<div v-for="item in info">
<div>
<!-- I compare 2 dates as strings, and if it's true, I want to show word 'Today' -->
<span v-if="(item.date | yymmdd === todayIs | yymmdd)" class="today">today</span>
<!-- else I want to show date as yyyy-mm-dd -->
<span v-else>{{item.date | yymmdd}}</span>
<!-- for some reason with filter date is NUMBER. why? in method and filter they should be stings -->
<span>{{ typeof (item.date | yymmdd)}}</span>
<span>{{ typeof (todayIs)}}</span>
</div>
</div>
</div>
vue:
new Vue({
el: "#app",
data: {
info: [
{ date: "2020-02-01 10:00", text: "first text" }, // date format from backend
{ date: "2020-02-02 15:00", text: "second text" },
{ date: "2020-02-03 15:00", text: "third text" },
{ date: "2020-02-04 18:00", text: "fourth text" },
],
todayIs: null
},
methods: {
today() {
var today = new Date(),
todayDate = ('0'+today.getDate()).slice(-2),
todayMonth = ('0'+ (today.getMonth() + 1) ).slice(-2),
todayYear = today.getFullYear();
var day = '';
day = todayYear + '-' + todayMonth + '-' + todayDate;
this.todayIs = day;
}
},
filters: {
// cut yyyy-mm-dd format and return date as string
'yymmdd': function (date) {
var newDay = new Date(date),
currentDate = ('0'+newDay.getDate()).slice(-2),
currentMonth = ('0'+ (newDay.getMonth() + 1) ).slice(-2),
currentYear = newDay.getFullYear();
var day = '';
day = currentYear + '-' + currentMonth + '-' + currentDate;
return day;
}
},
created: function () {
this.today()
},
})
最佳答案
您只能在 Mustache 插值和 v-bind 表达式中使用过滤器
(后者在 2.1.0+ 中受支持)。因此它不能像在 v-if
中使用它一样使用。
您可以在方法中创建一个函数来比较日期,如下所示:
compareWithToday(date){
return this.$options.filters.yymmdd(date) === this.todayIs;
}
然后使用此函数来评估模板中的 v-if
标志
<span v-if="(item.date | yymmdd === todayIs | yymmdd)" class="today">today</span>
以上内容应替换为以下内容:
<span v-if="compareWithToday(item.date)" class="today">today</span>
这是上面的工作jsfiddle:https://jsfiddle.net/17mp6ofe/
关于javascript - Vuejs如何将日期与列表中的过滤器进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026130/