How to set URL query params in Vue with Vue-Router

前端 未结 9 734
梦如初夏
梦如初夏 2020-12-23 20:24

I am trying to set query params with Vue-router when changing input fields, I don\'t want to navigate to some other page but just want to modify url query params on the same

9条回答
  •  有刺的猬
    2020-12-23 20:29

    If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.

    This works, since you are making an unreferenced copy:

      const query = Object.assign({}, this.$route.query);
      query.page = page;
      query.limit = rowsPerPage;
      await this.$router.push({ query });
    

    while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated error:

      const query = this.$route.query;
      query.page = page;
      query.limit = rowsPerPage;
      await this.$router.push({ query });
    

    Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.

      const { page, limit, ...otherParams } = this.$route.query;
      await this.$router.push(Object.assign({
        page: page,
        limit: rowsPerPage
      }, otherParams));
    );
    

    Note, while the above example is for push(), this works with replace() too.

    Tested with vue-router 3.1.6.

提交回复
热议问题