vue.jsv-model

How do I set a default value for v-model using computed property


I have two input fields for dates: to and from.

I want the user to be able to select dates that I will send a request to the backend. That is why I am using a computer property - in the setter I will validate the dates to make sure from is less than to and to is not less than from.

How do I set default values for those inputs?

I am using computed properties so I can set default values for both inputs. One value is set to now, the other is 1 week ago.

<template>
<div class="logs-listing-table">
    <div class="mb-1 filter-actions-wrapper">
    <input type="date" v-model="this.fromDate">
    <input type="date" placeholder="this.toDate">
    </div>
  </div>
</template>

<script>
export default {
  name: 'BnbReport',
  data () {
    return {
        fromDate: this.fromDateDefault(),
        toDate: this.toDateDefault()
    }
  },
  computed: {
    fromDateDefault () {
      var previousPeriod = new Date()
      previousPeriod.SetDate(previousPeriod.getDate() - 7)
      previousPeriod.toISOString().substr(0, 10)
      this.fromDate = previousPeriod
      return this.fromDate
      },
      toDateDefault () {
          var today = new Date()
          today.toISOString().substr(0, 10)
          this.toDate = today
          return this.toDate          
      }
  }
}
</script>

However, eslint throws me an error:

Unexpected side effect in "fromDateDefault" computed property

Unexpected side effect in "toDateDefault" computed property


Solution

  • You can add get and set functions into your computed property.

    HTML:

    <input type="date" v-model="fromDateDefault">
    
    

    JS:

    computed: {
        fromDateDefault: {
          get() {
            //your validation
            return this.fromDate;
          },
          set(val) {
            this.fromDate = val;
          },
        },
      }
    

    You can read more about the setters and getters in the official doc: https://v3.vuejs.org/guide/computed.html#computed-properties