【发布时间】:2019-11-20 12:59:03
【问题描述】:
我想使用支持本地化的日期选择器组件。我创建了这个日期选择器示例
HTML:
<div id="app">
<v-app id="inspire">
<v-menu
:value="showDatePicker"
max-width="290px"
>
<template v-slot:activator="{ on }">
<v-text-field
:value="formattedDate"
readonly
clearable
label="Date"
v-on="on"
:rules="rules"
:required="true"
@input="selectDate"
></v-text-field>
</template>
<v-date-picker
:value="date"
:locale="currentLocale"
no-title
@input="selectDate"
/>
</v-menu>
</v-app>
</div>
JS:
new Vue({
el: '#app',
data: () => ({
showDatePicker: false,
date: '',
currentLocale: 'de',
rules: [
value => this.validateDate(value) || 'Invalid date'
]
}),
computed: {
formattedDate: function () {
const formattedDate = this.date
// !! format the date based on this.currentLocale !!
return formattedDate
}
},
methods: {
selectDate: function(newDate) {
this.showDatePicker = false;
this.date = newDate;
},
validateDate: function(date){
// !! validate iso date here !!
return true
}
}
})
https://codepen.io/anon/pen/ydZqxd?editors=1010
日期选择器组件本身返回 iso 格式的日期。我想使用它,但我也想为用户显示语言环境日期格式。事情变得棘手,因为我想用 iso 格式验证日期,但文本字段使用格式化的日期作为其值。因此,当涉及到验证时,文本字段会传入格式化日期,但这是 错误 值。它应该是 iso 日期。
拥有像 display/value 这样的东西会很酷,尽管它对文本字段没有意义......
有没有办法将 iso 格式传递给验证规则并仅显示格式化的日期?
【问题讨论】:
-
你不能通过 Date 运行事情吗?
new Date(arbitrary valid date string).toISOString()将为您提供保证有效的 ISO 日期,thatsamedateobject.toLocaleString()将为您提供本地化版本。 -
否,因为它传递的是语言环境日期而不是传递“真实”日期字符串
标签: vue.js vuetify.js