Update component on query string change

Hi,

I am using vue router with history mode. I have a search implemented with this URI: /search?q=one

To execute the search, a separate components does:

                this.$router.push({
                    name: 'search',
                    query: {
                        q: this.searchInput
                    }
                });

On the search results component, I load the search results on mounted(), but when a new search is performed (URL changes to /search?q=two) nothing changes on the component. I can see that the search is actually performed, on chrome developers tool, but the VUE data property results is not updated.

        mounted() {
            this.isLoading = true;
            api.ListEvents({
                q: this.$route.query.q
            }).then((res) => {
                this.results = res.events;
                this.isLoading = false;
            }).catch(() => {
                this.isLoading = false;
            });
        }

None of the data properties are updating on the search result component according to vue dev tools.

If I navigate away from research results and perform a search, the results do get updated.

1 Like

You should use a watch on the $route property to trigger the api call when the query changed.

Watching $route.query for changes alone doesn’t work when searching from another page. I am guessing it’s because the SearchResult component doesn’t exist until I $router.push and it only starts watching then.

This is how I currently do it, but it triggers the API twice for every search I do.

        methods: {
            doSearch() {
                this.isLoading = true;
                api.ListEvents({
                    q: this.$route.query.q
                }).then((res) => {
                    this.results = res.events;
                    this.isLoading = false;
                }).catch(() => {
                    this.isLoading = false;
                });
            }
        },

        watch: {
            '$route.query.q'() {
                this.doSearch();
            }
        },

        mounted() {
            this.doSearch();
        }
4 Likes

That would be weird, as mounted only runs on component creation, and the watch whole not run in the first query change after the component has already been created.

set immediate: true in order to run in the first query change