P
P
p3trukh1n2019-06-06 11:09:21
JavaScript
p3trukh1n, 2019-06-06 11:09:21

How to force the property to be calculated every time the fields are changed?

I'm making a calculator using Vue.JS. I
need to calculate the difference in dates.
But, of course, the code you see below only executes it the first time, on load.
How can I make this property recalculate every time one of the dates changes?

var vue = new Vue({
    el: '#calc',
    data: {
        dates: [{
            enterDate: '6.6.2019',
            leaveDate: '7.6.2019'
        }]
    },
    methods: {
        getDifference(date1, date2) {
            var d1 = date1.split('.'),
                d2 = date2.split('.');
            d1 = new Date(`${d1[1]}-${d1[0]}-${d1[2]}`);
            d2 = new Date(`${d2[1]}-${d2[0]}-${d2[2]}`);
            return Math.ceil(Math.abs(d2.getTime() - d1.getTime()) / (1000 * 3600 * 24));
        }
    }
})

<div id="calc">
        <div class="input-row" v-for="(date,index) in dates" :key="index">
            <input type="text" class="date-input calc-input calc-enterdate" placeholder="Дата въезда" :value="date.enterDate">
            <input type="text" class="date-input calc-input calc-leavedate" placeholder="Дата выезда" :value="date.leaveDate">
            <input type="text" class="date-input calc-input calc-dayscount" placeholder="Дата выезда" :value="getDifference(date.enterDate, date.leaveDate)">
        </div>
    </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kulakov, 2019-06-06
@kulakoff Vue.js

You need to add feedback for the fields you change in order to trigger an update on the component as well. In your version, it should work like this:

<input type="text" class="date-input calc-input calc-enterdate" placeholder="Дата въезда" v-model="date.enterDate">
<input type="text" class="date-input calc-input calc-leavedate" placeholder="Дата выезда" v-model="date.leaveDate">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question