Vue组件无法在新的$ router.push上重新渲染

时间:2017-11-07 12:53:47

标签: javascript web vue.js vuejs2 vue-component

所以我有这个SearchResult组件,当由vue-router调用时,从YouTube API v3获取一个对象将收到的对象作为道具传递给几十个子组件。我有一个搜索栏,使用$router.push(/search/ + this.query)来更改路线并显示此组件。

问题在于它第一次使用效果很好,或者当我使用其他路线搜索时效果很好。但是,当我再次搜索没有组件重新呈现API的新结果时。即使我已为this.$route.params.query添加了观察者。这是SearchResult.vue组件。

<template>
<div>
  <app-banner></app-banner>
  <div v-if="resultIds">
    <div v-for="resId in resultIds.items">
      <vid-preview :vidId="resId.id.videoId"></vid-preview>
    </div>
  </div>
</div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      resultIds: null,
      errors: []
    }
  },
  watch: {
    '$route.params.query' (newQuery, oldQuery) {
      this.$router.push('/search/' + newQuery) //This code executes but no change visible on screen.
    }
  },
  created() {
    axios.get(`https://www.googleapis.com/youtube/v3/search/`, {
      params: {
        part: 'id',
        q: this.$route.params.query,
        order: 'relevance',
        maxResults: '50',
        key: '{API KEY}'
      }
    }).then(res => {
      this.resultIds = res.data;
    }).catch(e => {
      this.errors.push(e);
    })
  }
}
</script>

1 个答案:

答案 0 :(得分:4)

应该是这样的:

'$route.params.query' (newQuery, oldQuery) {
  this.$router.push({
    path: '/search/' + newQuery
  })
}

目前:

'$route.params.query' (newQuery, oldQuery) {
  this.$router.push('/search/' + newQuery) //This code executes but no change visible on screen.
}
相关问题