0

When I'm trying to use Template strings inside the data function in vuejs but, it always returns undefined any idea how to solve this ?

I was trying to make a URL for an API call dynamic

Cheers,

  data() {
    return {
      baseUrl: `https://example.com/api/json?key=${this.key}`,
      key: "IzNDU2Nzg5MDEyMzQ1Njc"
    };
  }

2 Answers 2

1

This is a JavaScript issue. If you run the following simple example in JavaScript you'll get a "is not defined" error (when running in strict mode).

{ a: `${b}`, b: "123" }
> VM246:1 Uncaught ReferenceError: b is not defined

You can't reference an adjacent variable ('key' in your example) in an object literal declaration.

You can use a Vue.je computed property for baseURL:

computed: {
  baseUrl() {
    return `https://example.com/api/json?key=${this.key}`;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you works like a charm, appreciate. so just for knowledge when you mentioned " This is a JavaScript issue " how can I deal with it in js ?
0

The data property cannot be made dynamic. Use a computed property like below:

computed: {
    baseUrl() {
        return `https://example.com/api/json?key=${this.key}`
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.