Simplify JS URL construction with the JS version of the add_query_arg function, addQueryArgs.
Those of you who are familiar with WordPress development have likely used theadd_query_arg functionHe can easily help us to add new query parameters to a URL to get a new URL.
With the development of the WordPress Gutenberg editor, WordPress ported this function to the JavaScript language, changing the name of the JS version of the function toaddQueryArgsis as@wordpress/url libraryof a function released. Today through a piece of code for you to demonstrate the use of the change function.
First we need to install this library into our project dependencies.
npm install @wordpress/url --save
Then we can import and use it in our project.addQueryArgsThis function is up.
import {addQueryArgs} from '@wordpress/url';
Here's a method from the nuxt project we developed to filter data based on multiple criteria. First we build an array of default parameters, then we add different elements to this array depending on the filter item that the user clicks on. Finally, we pass this array of parameters into addQueryArgs to build a URL to request the Rest API to query the data.
fetchData() {
let args = {
'page' : this.page, 'categories' : '9,10,11,12,13', 'page' : this.
'tax_relation' : 'AND',
};
if (this.orderBy) {
args.orderBy = this.orderBy;
}
if (this.type) {
args.huxing = this.type; } if (this.type) { args.orderby = this.
}
let exclude_cats = _.difference(_.rest(_.pluck(this.storeOptions, 'value')), [this.store]);
if (this.store) {
args.categories_exclude = exclude_cats;
}
if (this.level) {
args.tags = this.level; } if (this.store) { args.categories_exclude = exclude_cats; }
}
return this.$api.get(addQueryArgs('/api/posts', args));
},
As you can see, relative to the previous method of using JavaScript character connection, this method of code readability is much better, the logic is also very clear, very convenient for later maintenance.
In addition to the ones described in this articleaddQueryArgsfunction, the @wordpress/url library also provides some very useful functions for handling URLs, such as:getQueryArgs、getQueryStringAnd so on. Anyone who needs to handle URLs in front-end projects can try it out.