【问题标题】:Return result from watcher - Vue JS从观察者返回结果 - Vue JS
【发布时间】:2017-12-23 10:36:15
【问题描述】:

我需要返回我从 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 }},但这不会得到我需要的“cancelBy”变量数据。

【问题讨论】:

    标签: javascript vuejs2 watch


    【解决方案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>
    

    【讨论】:

    • 这正是我想要的。谢谢!
    • 你为什么把它改成 vm.cancelBy 而不是 this.cancelBy?
    • 箭头函数有时会改变 this 的上下文,使其不再指向 Vue 实例。我不记得这个例子中是否是这种情况,所以为了安全起见,我设置了一个引用。见Using "this" in Vue
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多