@Watch 未触发

DS_*_*per 2 typescript vue.js

所以我的hiearchy是这样设置的

  • 应用程序

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

在哪里

在 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;
  }

...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 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>
Run Code Online (Sandbox Code Playgroud)

然后,在我的 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>
Run Code Online (Sandbox Code Playgroud)

该项目和匹配@Watch不是得到触发,但与Vue公司-devtools它说,有数据......它打印出...那么,为什么我的@Watch不会被触发?

Ser*_*eon 5

在您的示例中,属性的matchand itempropsTimelineItemMetadata似乎不会随时间变化:它们只是在App组件安装时由组件设置。

正如我在这里读到的,似乎您需要将显式immediate参数传递给观察者,以使其在道具第一次更改时触发.

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

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