What I am trying to accomplish is when the page first loads I will use Axios using the base URL to pull back a JSON object. I then want to add query parameters to the base URL when a button is clicked. So something along the lines of if the base URL is 'test.com' when the button is clicked a query parameter would be added to the URL and Axios would run again pulling back a different JSON object. So the URL could look something like 'test.com?posttype=new'.
What I am currently doing is on create run Axios with the base URL and when the button is clicked run a method that runs Axios again but this time it adds the query parameters to the URL so in Vue it looks like:
created () {
axios
.get(this.jobsListURL)
.then(response => (this.jobsList = response.data.data))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
methods: {
getJobs: function () {
axios
.get(this.jobsListURL + '?' + this.AxiosParams)
.then(response => (this.jobsList = response.data.data))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
So in the above example jobsListURL is the base URL for the JSON object and AxiosParams is a method I am calling to add the parameters to the URL when the button is clicked. So when the button is clicked it is running the getJobs method to rerun Axios using the URL with the parameters. I am not sure if this is the best approach for this or if there is a better way of adding query parameters to the URL and grabbing the new JSON object this way.
Just looking for some feedback before I go to far down this route to see if there is a better approach for this?
You can use the second argument to .get
if you want to pass an object instead:
axios.get(this.jobsListURL, {
params: this.axiosParams
})
This is pretty much the same, but you don't have to do the string manipulation for the URL.
You can build that object like this:
computed: {
axiosParams() {
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
return params;
}
}