从观察者返回结果 - Vue JS

时间:2017-07-18 13:52:47

标签: javascript vuejs2 watch

我需要从Vue JS的观察者那里得到一个结果。

这是该组件的一部分。

<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>      

当我在console.log(cancelBy)时,我得到一些日期,然后我需要在模板中显示。我在模板中插入了我需要它的注释。我尝试使用{{date()}},{{date}},但是没有得到“取消”#39;我需要的可变数据。

1 个答案:

答案 0 :(得分:1)

只需添加新的数据属性cancelBy

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

然后在异步调用返回时设置:

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

在您的模板中,您可以执行以下操作:

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