11

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

2 Answers 2

33

v-model on 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.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That was exaclty what I need.
1

v-model binding

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

Emits events

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

1 Comment

While this code may solve the problem, to be a good answer it needs to explain why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.