typescript - @Watch 未触发

标签 typescript vue.js

所以我的hiearchy是这样设置的

  • 应用

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

在哪里

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

<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 NOT 被触发但是使用 Vue-devtools 它说有数据......并且它打印出来......所以为什么我的@Watch 没有被触发?

最佳答案

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

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

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

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

关于typescript - @Watch 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575272/

相关文章:

typescript - 以类作为参数并返回该类实例的函数的类型

没有 v-model 的 Vue.JS 复选框

javascript - el-table 中的自定义列标题没有反应

typescript - 从 Typescript 引用 DLL

typescript - 错误 TS2339 : Property 'x' does not exist on type 'Y'

node.js - Node 类型在 typescript 中不起作用

typescript - ionic 滑动手势不适用于手机

javascript - VueJs 中的 Highmaps...将 State 传递给 mapOptions

php - vuejs 预渲染 php 动态内容

vue.js - 为什么apollo在第一次请求时无法获取数据?