David
David

Reputation: 2007

Return result from watcher - Vue JS

I need to return a result I get from a watcher in Vue JS.

This is part of the component.

<template>

    <input name="date" v-model="date" id="date-picker">

    <div class="alert alert-info" role="alert">
      You must cancel {{ trip.in_advance }} days in advance from
      <div v-if="date !== ''">
          {{ date }}. 
          By {{ I need to display the result returned from the 'date' watcher here }}
          </div>
          <div v-else> 
          your selected booking date.           
      </div>
    </div>

 </template>

 <script>
    import moment from "moment";
    import VueMomentJS from "vue-momentjs";

    Vue.use(VueMomentJS, moment);

    export default{
        props: ['trip', 'user'],
        data() {
          return {
            date: ''
          }
        },
        watch: {
            date() {
                this.$http.get('/trip/dates/'+this.trip.id, this.$data).then(() => {
                    // Get the selected date, and format it
                    let bookingDate = moment(this.date).format("YYYY-MM-DD, HH:mm:ss a");

                    // Get the selected date, and subtract the "in advance" date from trip
                    let inAdvanceDate = moment(bookingDate).subtract(this.trip.in_advance, 'days');
                    let cancelBy = inAdvanceDate.format("YYYY-MM-DD, HH:mm:ss a");
                    console.log(cancelBy);

                }, (response) => {
                    console.log(response);
                });
            }
        }
      }
</script>      

When I console.log(cancelBy), I get some date, which then I need to display in the template. I inserted the comment where I need it in the template. I tried just using {{ date() }}, {{ date }}, but that wont get the 'cancelBy' variable data I need.

Upvotes: 0

Views: 2223

Answers (1)

thanksd
thanksd

Reputation: 55664

Just add a new data property cancelBy:

data() {
  return {
    date: '',
    cancelBy: null,
  }
},

And then set that when the async call returns:

let vm = this;
this.$http.get(...).then(() => {
  ...
  vm.cancelBy = inAdvanceDate.format("YYYY-MM-DD, HH:mm:ss a");
}

And in your template you could do something like this:

<div v-if="date !== ''">
  {{ date }}. 
  <span v-if="cancelBy !== null> 
    By {{ cancelBy }}
  </span>
</div>

Upvotes: 1

Related Questions