【问题标题】:@Watch not triggered@Watch 未触发
【发布时间】:2018-07-28 21:06:47
【问题描述】:

所以我的层次结构是这样设置的

  • 应用程序

    • 时间线项目
      • 时间线元数据

在哪里

在 app.vue 中 在挂载时,我做了一些 http 请求,在获取和处理数据时,我填充了一个时间线变量

<template>
  <div id="app">
    <div class="loading" v-show="loading">Loading ...</div>
    <table class="timeline">
        <TimelineItem v-for="event in timeline" :key="event.id" :item="event" :players="players" :match="match"></TimelineItem>
    </table>
  </div>
</template>


export default class App extends Vue {
  ... 

  public timeline: any[] = [];

  public mounted() {
    ...
    if (!!this.matchId) {
      this._getMatchData();
    } else {
      console.error('MatchId is not defined.  ?matchId=....');
    }
  }

  private _getMatchData() {
    axios.get(process.env.VUE_APP_API + 'match-timeline-events?filter=' + JSON.stringify(params))
      .then((response) => {
        this.loading = false;
        this.timeline = [];
        this.timeline = response.data;
  }

...
}

然后在我的 TimelineItem 我有这个:

<template>
  <tr>
    <td class="time">
      ...
      <TimelineItemMetadata :item="item" :match="match"></TimelineItemMetadata>

    </td>
  </tr>
</template>

....

@Component({
  components: {
    ...
  },
})
export default class TimelineItem extends Vue {
  @Prop() item: any;
  @Prop() match: any;
  @Prop() players: any;
}
</script>

然后,在我的 TimelineItemMetadata 中:

<template>
  <div>
    TEST1
    {{item}}
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';

@Component({})
export default class TimelineItemMetadata extends Vue {

  @Prop() item: any;
  @Prop() match: any;


  @Watch('match') onMatchChanged() {
    console.log('TEST');
  }
  @Watch('item') onItemChanged() {
    console.log('ITEM', this.item);
  }

  public mounted() {
    console.log('timeline metadata item component loaded');
  }

}
</script>

@Watch 项目和匹配项 不会 被触发,但使用 Vue-devtools 时,它说有数据......它会打印出来......所以为什么我的@Watch 没有被触发?

【问题讨论】:

  • 也许只是复制/粘贴的问题,但在您的TimelineItem 中,您没有在@Component 组件选项中设置TimelineItemMetada。此外,在您的 TimelineItemMetadata 中有一个定义 onMathcChanged 函数的错字(这应该与您的问题无关)
  • 是的,我包括了所有组件,因此 TimelineItemMetadata 正在显示和显示 {{item}} ....只是 @Watch 没有触发...感谢您的提示错别字...但是,是的,这是不相关的,没有解决问题:/已经在这个问题上几个小时了...无法解决它:'(

标签: typescript vue.js


【解决方案1】:

在您的示例中,TimelineItemMetadata 属性的 matchitem 属性似乎不会随着时间而改变:它们只是在安装时由 App 组件设置。

As I read here,您似乎需要将明确的immediate 参数传递给观察者,以使其在第一次道具更改时触发。

所以,我想你应该这样做:

// note typo is fixed
@Watch('match', {immediate: true}) onMatchChanged() {
  console.log('TEST');
}
@Watch('item', {immediate: true})) onItemChanged() {
  console.log('ITEM', this.item);
}

【讨论】:

  • 哎呀!它正在工作......就像一个魅力......非常感谢!你是救生员!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 2018-01-01
  • 1970-01-01
  • 2019-11-29
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多