[Vuejs]-Can I create new objects in Vue data() function?

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.

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.

Leave a comment