Home > Software engineering >  Set multiple query params in Vue
Set multiple query params in Vue

Time:06-03

I am looking for the best approach in Vue to set multiple query parameters for filtering (I have 3 filters), and to make URL work when the page is reloaded. I tried this : currentUser, currentNumOfReplies and filterKeyword have v-model in template.

data() {
  return {
    currentUser: null,
    currentNumOfReplies: null,
    filterKeyword: null,
  }
}

watch: {
  currentUser() {
    this.$router.push({ query: { user: this.currentUser } })
  },
  filterKeyword() {
    this.$router.push({ query: { keyword: this.filterKeyword } })
  },
}

when a user is selected, it is added to the URL, but then when a keyword is added it removes the user and then adds the keyword. Filters work here, all I want is to add filters to the URL when the user selects and when the page reloads to keep these filters.

CodePudding user response:

// ******* Data
data() {
    return {
        queryParams: {
            currentUser: null,
            currentNumOfReplies: null,
            filterKeyword: null,
        }
    }
}
// ***** Template
<input v-model="queryParams.currentUser" @input="setQuery" />


// ***** Methods
setQuery() {
    const query = {}
    Object.entries(this.queryParams).forEach(([key, value]) => {
        if (value) {
            query[key] = value
        }
    })
    this.$router.push({ query })
}

CodePudding user response:

data() {
  return {
    currentUser: null,
    currentNumOfReplies: null,
    filterKeyword: null,
  };
},
watch: {
  currentUser() {
    this.setQueryParams();
  },
  filterKeyword() {
    this.setQueryParams();
  },
},
methods: {
  setQueryParams() {
    const user = this.currentUser ? { user: this.currentUser } : null;
    const keyword = this.filterKeyword ? { keyword: this.filterKeyword } : null;
    const query = {
      ...user,
      ...keyword,
    };
    this.$router.push({ query });
  },
},
  • Related