我有以下情况:
<bl-card :subtitle="card.beforeChanged + ' ' + (card.changed | formatDate)" />
字幕需要通过组合两个字符串来设置。 card.beforeChanged
包含"上次更改为:">字符串,card.changed
变量包含日期时间字符串。通过 de formatDate()
日期时间字符串被格式化为可读日期。
字幕现在返回:"上次更改为:2069882880"。
问题:是否可以组合两个字符串,其中一个字符串一次性通过过滤器属性进行格式化?
通过一种方法让它工作。计算属性不是一个选项,因为日期字符串来自模板中的 for 循环。
方法:
formatDate: (date, format) => {
if (!date) return ''
if (!format) format = 'DD.MM.YYYY'
return moment(date).format(format)
}
实现:
<bl-column v-for="(card, index) in cards" :key="card.id">
<bl-card :index="index" type="section" action="drawer" :title="card.titleShort" :subtitle="(card.beforeChanged || '') + ' ' + formatDate(card.changed)" />
</bl-column>
为此,应使用计算机属性。
Vue.filter('formatDate', function (value) {
return moment(value).fromNow()
})
Vue.component('todo', {
computed: {
formatedText: function () {
return `${this.text} - ${Vue.filter('formatDate')(this.date)}`
}
},
props: ['text', 'date'],
template: '<li>{{ formatedText }}</li>'
});
var demo = new Vue({
el: '#demo',
data: {
todos: [
{text:'testing', date: new Date()},
{text:'old text', date: moment().subtract(7, 'days')}
]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="demo" v-cloak>
<p v-if="!todos.length">No todos at this moment.</p>
<ul v-else>
<todo v-for="t in todos" :text=t.text :date=t.date></todo>
</ul>
</div>