Amol Borkar
Amol Borkar

Reputation: 2609

Vue component not re rendering on new $router.push

So I have this SearchResult component which when invoked by vue-router, fetches an object from YouTube API v3 passes the recieved object as props to dozens of child components. I have a search bar which uses $router.push(/search/ + this.query) to change routes and display this component.

The problem is that it works great for the first time or when I'm using search from some other route. But when I search again the component doesn't re-renders with new results from the API. Even though I've added a watcher for this.$route.params.query. Here is SearchResult.vue component.

<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>

Upvotes: 1

Views: 3209

Answers (1)

Mandeep Gill
Mandeep Gill

Reputation: 4895

It should be like this :

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

currently :

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

Upvotes: 3

Related Questions