javascript 如何在vue js中设置当天的默认日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50720802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:14:44  来源:igfitidea点击:

how to set the default date of the day in vue js

javascripthtmldatevue.jsvuejs2

提问by Cedric Tegue

I would like to set the date of the day by default in my datepicker.

我想在我的日期选择器中默认设置当天的日期。

code:

代码:

<template lang="html">
  <input type="date" v-model="date">
</template>
<script lang="js">
export default {
name: 'component',
props: [],
mounted() {

},
data() {
  return {
    // date: new Date().toJSON.split('T')[0],
    date: new Date(),
  }
},
methods: {

},
computed: {

},
               }
</script>

it does not work unfortunately, I was told about moment js but I do not know how we use it

不幸的是它不起作用,有人告诉我关于 moment js 但我不知道我们如何使用它

回答by bbsimonbb

v-modelon a Date input works with a string in yyyy-MM-dd format. If you're happy to have strings in your model, not date objects, then just put your default date string in the date variable, like this.

v-model在日期输入上使用 yyyy-MM-dd 格式的字符串。如果您很高兴在模型中有字符串,而不是日期对象,那么只需将默认日期字符串放在日期变量中,就像这样。

date : new Date().toISOString().slice(0,10)

Here's a running example. A name has been changed to avoid having variable names close to reserved keywords !

这是一个运行示例。已更改名称以避免变量名称接近保留关键字!

vm = new Vue({
  el : '#vueRoot',
  data : { myDate : new Date().toISOString().slice(0,10) }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div  id='vueRoot'>
    <input type='date' v-model='myDate'>
    <br>
    {{myDate}}
</div>

Of course you may want to have dates as date objects in your model, if you want to format or compare them. In that case, you should avoid v-model and code the two sides of your binding separately, like this.

当然,如果您想格式化或比较它们,您可能希望将日期作为模型中的日期对象。在这种情况下,您应该避免使用 v-model 并分别对绑定的两侧进行编码,如下所示

回答by Ketan

v-modelbinding

v-model捆绑

<datepicker v-model="state.date" name="uniquename"></datepicker>

Emits events

发出事件

<datepicker 
    @selected="doSomethingInParentComponentFunction" 
    @opened="datepickerOpenedFunction"
    @closed="datepickerClosedFunction"
>
</datepicker>