0

I'm creating a new Audio() object inside a Vue component's data() { ... } function, but I got concerned about if this is unnecessarily creating more Audio objects.

I can't seem to find when or how the data() function is called, but I also couldn't find any examples that crates a new object in the data function.

Is it ok to create new objects inside data() ? Or should I leave those initializations to the created() function?

2 Answers 2

1

Read the documentation about data() : https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

a component’s data option must be a function, so that each instance can maintain an independent copy of the returned data object.

It is the right way to do it.

Your new object will be instantiated like so :

data() {
  // new object returned
  return {
    audio: new Audio()
  }
}

If you want to have a global object to avoid multiple instance of audio, think about attaching it to the global Vue instance or using Vuex depending on what you need.

Sign up to request clarification or add additional context in comments.

Comments

0

It's completely fine to create new objects inside the returned object of the data() function, that's what is meant for. More informations here.

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.