I'm trying to make something work with my vue app
I made constants.js file in which i just declare some of URLs I plan to recycle instead of rewriting them every time, but some of them require IDs of stuff
#Example of constant definined in constants.js
export const useVariables = `https://myapiserver.com/iNeedVar1Here/${var1}/iNeedVar2here/${var2}`
And now I want to use this constant in my vue app and pass the variables where I need them, before sending the actual request
getItem() {
let var2 = this.formValues.item2;
let var1 = this.formValues.item1;
if (item != null) {
axios.get(useVariables)
.then((res) => {
console.log(res.data)
})
.catch(err => console.log(err));
}
else {
alert('Select an item before preceding')
}
CodePudding user response:
Your constant is static, it's not like a computed
property or anything it's just a plain string so it won't work. Instead, you can create a function that will build and return the URL like this :
export const useVariables = (var1, var2) => `https://myapiserver.com/iNeedVar1Here/${var1}/iNeedVar2here/${var2}`
And then you can build the constant like this :
getItem() {
let var2 = this.formValues.item2;
let var1 = this.formValues.item1;
if (item != null) {
axios.get(useVariables(var1, var2))
.then((res) => {
console.log(res.data)
})
.catch(err => console.log(err));
} else {
alert('Select an item before preceding')
}
}
CodePudding user response:
As per your current implementation, You will get the below error :
var1 was used before it was declare, which is illegal for const variables
var2 was used before it was declare, which is illegal for const variables
You have to pass these variables into a method and then have to return the concatenated string. You can give a try to this :
In some other utility file :
export function getAPIUrl(var1, var2) {
return `https://myapiserver.com/iNeedVar1Here/${var1}/iNeedVar2here/${var2}`
}
In component :
import * as ApiUtil from '@/util/ApiUtil
axios.get(ApiUtil.getAPIUrl(var1, var2))
.then((res) => {
console.log(res.data)
})
.catch(err => console.log(err));