Reputation: 1493
That is my problem, the dates comes with that format "9999-99-99 00:00:00
", but i want to set it to "9999-99-99
". But it came in an array, and has a lot fields. My question is, how to overwrite the value using the vuejs?
new Vue({
el: '#app',
data: () => ({
fields: [{
"id": 1,
"date": "2019-02-05",
},
{
"id": 2,
"date": "2018-12-01 00:00:00",
},
{
"id": 3,
"date": "2017-02-05 00:00:00",
}
]
}),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template>
<div v-for="field in fields" :key="field.id">
<input v-model="field.date" type="date">
</div>
</template>
</div>
I tried to use computed method, but it just call this when i set the value manually. Then i tried this and it works. But, is this an efficient way to do this?
new Vue({
el: '#app',
methods: {
formatValue( key){
this.fields[key].date = this.fields[key].date.split(" ")[0];
}
},
data: () => ({
fields:
[
{
"id":3958,
"date":"2019-02-05",
},
{
"id":3959,
"date":"2018-12-01 00:00:00",
},
{
"id":3960,
"date":"2017-02-05 00:00:00",
}
]
}),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template>
<div v-for="(value, key) of fields" :key="key">
<input v-model="fields[key].date" type="date" >{{value.date}} {{formatValue(key)}}
</div>
</template>
</div>
The second method runs twice, because he had to re-render, so it's not a good idea.
Upvotes: 1
Views: 932
Reputation: 9180
I would use a filter with momentjs for this:
new Vue({
el: '#app',
data: () => ({
fields: [{
"id": 1,
"date": "2019-02-05"
},
{
"id": 2,
"date": "2018-12-01 00:00:00"
},
{
"id": 3,
"date": "2017-02-05 00:00:00"
}
]
}),
filters: {
formatDate(val) {
return moment(val).format('YYYY-MM-DD');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(value, key) in fields" :key="key">
<input v-model="fields[key].date" type="date" /> {{value.date | formatDate}}
</div>
</div>
Upvotes: 1
Reputation: 870
https://jsfiddle.net/we8o3p7r/2/
function makeCorrectDate(str) {
return new Date(str).toISOString().split('T')[0]
}
new Vue({
el: '#app',
data: () => ({
fields: [{
"id": 1,
"date": makeCorrectDate("2019-02-05"),
},
{
"id": 2,
"date": makeCorrectDate("2018-12-01 00:00:00"),
},
{
"id": 3,
"date": makeCorrectDate("2017-02-05 00:00:00"),
}
]
}),
});
Another way to do it:
<div id="app">
<template>
<div v-for="field in fields" :key="field.id">
<input
:value="makeCorrectDate(field.date)"
@input="field.date = $event.target.value"
type="date"
/>
<div>{{ field.date }}</div>
</div>
</template>
</div>
Upvotes: 1