0

I have a date picker on my page which I initialize with today's date. Before porting to Vue I used:

document.getElementById("entryDate").valueAsDate = new Date()

Courtesy of https://stackoverflow.com/a/13322910/2672848

But this doesn't work for me in Vue. Obviously I need to access the element itself to get the valueAsDate property, so I do:

const entryDate = ref(null)
const entryDateElem = ref(null)

onMounted(() => {
  entryDateElem.value.valueAsDate = new Date()
})

and in my template:

<input type="date" ref="entryDateElem" v-model="entryDate"></input>

but the date picker value is unchanged. If I use the alternate answer in that same Stack Overflow post (setting the value directly) it does work, as expected.

onMounted(() => {
  entryDate.value = new Date().toISOString().substr(0, 10)
})

But why doesn't valueAsDate work? I have checked that entryDateElem.value refers to the element in question.

Juckix
  • 35
  • 1
  • 2
  • 7
  • 1
    Your `valueAsDate` code works fine in this [demo](https://codesandbox.io/s/date-picker-v-model-in-vue-3-zy1un?file=/src/App.vue). – tony19 Mar 28 '21 at 22:23

1 Answers1

3

In vue it's not recommended to manipulate the DOM using vanilla JS because Vue is data-driven framework which means that your input should be bound to a data property and it changes based on that data not by assigning raw data to its attributes like :

entryDateElem.value.valueAsDate = new Date() // you're manipulating directly the DOM ❌

the right way :

entryDate.value = new Date() // you're manipulating the data ✔
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • entryDate.value = new Date() does not work, but entryDate.value = "YYYYMMDD" does. Not sure what the issue was for me – Juckix Jun 30 '21 at 11:29