0

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')
            }
1
  • You should get this error var2 & var1 is used before its declare, which is illegal for const variables Commented May 19, 2022 at 14:14

2 Answers 2

2

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')
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.