Using variables with url constants in vue.js
P粉547170972
P粉547170972 2024-02-21 12:48:01
0
1
474

I'm trying to get my vue application to work

I made the constants.js file in which I just declared some URLs that I intended to recycle instead of rewriting them every time, but some of them required IDs of things

#Example of constant definined in constants.js
export const useVariables = `https://myapiserver.com/iNeedVar1Here/${var1}/iNeedVar2here/${var2}`

Now I want to use this constant in my vue application and pass the variable where needed 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')
            }

P粉547170972
P粉547170972

reply all(1)
P粉903052556

Your constant is static, it's not like a computed property or anything, it's just a regular string, so it doesn't work. Instead, you can create a function that builds and returns the URL like this:

export const useVariables = (var1, var2) => `https://myapiserver.com/iNeedVar1Here/${var1}/iNeedVar2here/${var2}`

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')
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template