Home > Enterprise >  trigger fetch if there's query params on route
trigger fetch if there's query params on route

Time:08-18

I'm Trying to filter records And I'm putting the filter params on route this.$route.query.

I have the filter on fetch :

  async fetch() {
     this.triggerFilter = true;
      const query = {
        limit: this.pageSize,
        page: this.currentPage,
        field: this.field,
        lang: this.lang,
        cost: this.range,
      };
      if (!this.field) delete query.field;
      if (!this.lang) delete query.lang;
      this.$router.push(
        this.localePath({
          name: "all-slug",
          query: query,
        })
      );

      this.sorted = true;
      let params = [];
      for (let key in query)
        params.push(
          `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`
        );
      const queryString = params.join("&");

      await this.$store.dispatch(
        "myaction",
        encodeURI("/api/ap"   this.$route.params.slug   "?"   queryString '&locale=' this.$i18n.locale)
      );
        this.triggerFilter = false
  },

I'm trying to make the function trigger if there are query parameters on the route if the user refreshed the page .

If i refresh the page and console log this.$route.query on fetch function i get {}

I just don't want to use mounted or created to call a method .

any idea how can this be achieved?

I'm using nuxt 2.

CodePudding user response:

You can access the route params with this.$route.params.{name of your param}. Maybe that's the issue?

CodePudding user response:

This kind of code totally works.

<template>
  <div>nice index page</div>
</template>

<script>
export default {
  async fetch() {
    if (this.$route.query.trigger === 'yes') {
      const call = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      const response = await call.json()
      console.log('response', response)
    }
  },
  fetchOnServer: false, // set this if you want to debug the call only on client-side
}
</script>

Type http://localhost:3000/?trigger=yes if you want fetch to call JSON placeholder's API. Type http://localhost:3000/?trigger=no (or whatever) otherwise.


As shown below

enter image description here

enter image description here

PS: this also totally works with this.$route.params too of course.

  • Related