【问题标题】:How to watch multiple properties in Vue component?Vue组件中如何查看多个属性?
【发布时间】:2019-04-20 17:21:45
【问题描述】:

当其他几个属性之一更新时,我正在尝试更新 Vue 组件属性 station。它不能用作计算属性,因为计算属性是同步的,这需要 API 请求。

基于issue reply in Vue core,我在vm.$watch 上找到了文档。这看起来是我需要的,但我不知道应该如何在这个组件上下文的上下文中实现它。

我认为我应该在文档中使用this 代替vm,但我不确定。再说一次,在箭头函数左侧使用this,这是$watch 的第一个参数,会引发类似Invalid left-hand side in arrow function parameters 的错误。

我对@9​​87654330@ 的使用位于以下组件代码的末尾。我不断收到的错误是:Failed watching path: "[object Object]" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.(我以为我是...)

<template lang="html">
  <div>
    {{ station }}
  </div>
</template>

<script>
import ApiService from '@/services/ApiService';

export default {
  name: 'Chart',
  props: {
    mode: String,
    toDate: String,
    toTime: String
  },
  data() {
    return {
      stationId: 3069,
      station: {}
    };
  },
  watch: {
    station: function() {
      // Render function
    }
  },
  methods: {
    getInfo: async function(opts) {
      const stationData = await ApiService[this.mode]({
        id: opts.id,
        toTime: `${opts.toDate}T${opts.toTime}`,
        fromTime: `${opts.fromDate}T${opts.fromTime}`
      })
        .then(res => {
          return res.data.station.properties;
        })
        .catch(err => {
          console.error(err);
          return {};
        });

      return stationData;
    }
  },
  created: function() {
    // MY WATCHING STARTS HERE  
    this.$watch(
      () => return {
        mode: this.mode,
        stationId: this.stationId,
        toDate: this.toDate,
        toTime: this.toTime
      },
      async function(data) {
        this.station = await this.getInfo({
          mode: data.mode,
          id: data.stationId,
          toDate: data.toDate,
          toTime: data.toTime
        }).then(res => {
          return res;
        });
      }
    );
  }
};
</script>

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    您的观察者正在返回箭头函数。应该是这样的:

    this.$watch(
      () => {
         return {
           mode: this.mode,
           stationId: this.stationId,
           toDate: this.toDate,
           toTime: this.toTime
         }
      },
    

    此代码无效使用:

    () => return { 
    

    如果没有使用大括号,箭头函数会隐式返回值。所以,你也可以使用like:

    this.$watch(
      () => ({
         mode: this.mode,
         stationId: this.stationId,
         toDate: this.toDate,
         toTime: this.toTime
      }),
    

    注意,括号用于返回一个对象。您可能还想进一步阅读this post

    【讨论】:

    • 当然是这样的傻事。谢谢!
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 2021-05-23
    • 2021-12-27
    • 2012-08-10
    • 2020-12-29
    • 2015-09-17
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多