Home  >  Q&A  >  body text

Using variables with url constants in vue.js

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粉547170972P粉547170972241 days ago401

reply all(1)I'll reply

  • P粉903052556

    P粉9030525562024-02-22 00:13:19

    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')
      }
    }
    

    reply
    0
  • Cancelreply