I need to submit a form using computed property in Vue.js. The end_saving
is computed from start_saving
and duration
. I need to use saving.end_saving
in v-model
so I can submit the value in a POST method via Axios.
<template>
......
<b-form-datepicker
locale="id"
:value="endSaving"
@input="saving.end_saving= $event.target.value"
></b-form-datepicker>
......
</template>
....
data() {
return {
saving: {
start_saving: "",
duration: "",
end_saving: "",
},
computed: {
endSaving: {
get: function () {
return moment(this.saving.start_saving)
.add(this.saving.duration, "days")
.subtract(1, "days")
.format("YYYY-MM-DD");
},
set: function (newValue) {
return (this.saving.end_saving = newValue);
},
},
},
methods: {
submitForm() {
axios
.post("/api/saving", this.saving)
.then(
(response) =>
(window.location.href = `/saving/${response.data.id}`)
)
.catch((error) => console.log(error));
},
}
But, every time I submit the form, the end_saving
is always null
.
Sounds like you would be better off computing the entire savings
object.
For example
data: () => ({
start_saving: "",
duration: 0
}),
computed: {
saving: ({ start_saving, duration }) => ({
start_saving,
duration,
end_saving: moment(start_saving).add(duration - 1, "days").format("YYYY-MM-DD")
})
}
Then bind your two form inputs to start_saving
and duration
<b-form-datepicker
locale="id"
v-model="start_saving"
></b-form-datepicker>
<input type="number" v-model.number="duration">
and use this.saving
in your Axios POST request (like you currently have)
axios.post("/api/saving", this.saving)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.