search

Home  >  Q&A  >  body text

Remove query items from router

<p>I am using the <code>replace</code> method in Vue to add <code>query</code> to the current URL. If the value doesn't exist, I assign it as <code>undefined</code>. </p> <pre class="brush:js;toolbar:false;">this.$router.replace({ name: "admin-frs", query: { limit: this.pageSize, page: this.currentPage, sort: this.sortbyapi || undefined, language: this.sortbyapiLang || undefined, }, }) </pre> <p>This will cause the query items to disappear from the URL when the query data is updated, which is acceptable. </p> <p>But it does not remove it from the query object. </p> <p>Is there a better way than this? </p> <p>Also, is it possible to get the query items from the route, like <code>&limit=10...etc</code>? </p>
P粉005134685P粉005134685463 days ago497

reply all(1)I'll reply

  • P粉982009874

    P粉9820098742023-08-26 00:16:34

    If I understand correctly, the OP wants the operation to be passed to the query object of router.replace. Can be implemented using standard js.

    First, explicitly name a query variable...

    let query = $router.query;

    To delete an attribute, you can use the js delete operator. For example, to delete query.limit...

    // 删除limit属性
    if (!this.pageSize) delete query.limit;

    Alternatively, if you are building this query, you can not add the limit attribute at the beginning...

    let query = {};
    if (this.pageSize) query.limit = this.pageSize;
    if (this.currentPage) query.page = this.currentPage;
    // 其他属性也是类似的处理
    // query现在只包含上述选择的属性

    After doing any of these operations, pass the variables to the router...

    $router.replace({ name: "admin-frs", query });

    To convert it to a string, there are probably several ways, including those from many libraries you may have, but the native way is...

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

    reply
    0
  • Cancelreply