Remove query items from router
P粉005134685
P粉005134685 2023-08-25 22:53:17
0
1
494
<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粉005134685
P粉005134685

reply all(1)
P粉982009874

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("&");
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template