VueJS:如何绑定日期时间?

Ton*_*ony 3 vuejs2

我从WebAPI接收到具有以下属性的JSON对象:

"BirthDate": "2018-02-14T15:24:17.8177428-03:00",
Run Code Online (Sandbox Code Playgroud)

HTML:

<input type="date" v-model="BirthDate" />
Run Code Online (Sandbox Code Playgroud)

我使用VueJS绑定了该对象,但是VueJS在控制台中给出了以下消息:

The specified value "2018-02-14T15:24:17.8177428-03:00" does not conform to the required format, "yyyy-MM-dd".
Run Code Online (Sandbox Code Playgroud)

在这种情况下,唯一相关的部分是2018-02-14,我可以舍弃其他信息。

我试图创建一个双向过滤器以将该日期时间转换为所需的格式,但没有成功。查看VueJS双向过滤器

如何将日期/时间格式转换并绑定到HTML日期输入所需的日期格式?

acd*_*ior 6

考虑到myDate您的财产,可以使用:

<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
                   @input="myDate = $event.target.valueAsDate">
Run Code Online (Sandbox Code Playgroud)

由于v-model 只是语法糖:value@input,你可以用它们来代替。在这种情况下,我们使用和更改了它们(将其格式化为String输入到Date对象的日期的输出,反之亦然)。

查看下面的演示和注意事项。

<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
                   @input="myDate = $event.target.valueAsDate">
Run Code Online (Sandbox Code Playgroud)
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    myDate: new Date('2011-04-11T10:20:30Z')
  },
  methods: {
    setMyDateToToday() {
    	this.myDate = new Date();
    },
    addADayToMyDate() {
      if (this.myDate) // as myDate can be null
        // you have to set the this.myDate again, so vue can detect it changed
        // this is not a caveat of this specific solution, but of any binding of dates
        this.myDate = new Date(this.myDate.setDate(this.myDate.getDate() + 1));
    },
  }
});
// Notes:
// We use `myDate && myDate.toISOString().split('T')[0]` instead
// of just `myDate.toISOString().split('T')[0]` because `myDate` can be null.

// the date to string conversion myDate.toISOString().split('T')[0] may
// have timezone caveats. See: https://stackoverflow.com/a/29774197/1850609
Run Code Online (Sandbox Code Playgroud)


Tah*_*abi 4

我认为这与 vueJs 无关,输入type="date"需要 YYYY-MM-DD 格式的日期,或者为空,请参见此处: https: //developer.mozilla.org/en-US/docs/Web/HTML/Element/input/日期

如果将日期对象拆分为日期和时间字段会更好