2

I want to store object in vue, it should be available for entire instance and not be reactive. Normally (with reactive) I would use 'data' like this:

new Vue({
  data: myObject
})

But in fact myObject don't need to change so I think making it reactive is bad. Is there any method to do this?

6
  • Reference it globally? window.myObject = myObject Commented Sep 12, 2017 at 5:11
  • I was thinking more about vue solution. I want to use it only in vue instance, I don't want littering global namespace Commented Sep 12, 2017 at 5:15
  • 1
    You might want to be looking into Vuex. Commented Sep 12, 2017 at 5:18
  • @RuChernChong I am using vuex already. Any more details? Commented Sep 12, 2017 at 5:20
  • @Bogdan set your myObject into the Vuex state and don't provide any mutators Commented Sep 12, 2017 at 5:22

2 Answers 2

2

You can use Vue Instance Properties.

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype:

Vue.prototype.$appName = 'My App'

Now $appName is available on all Vue instances, even before creation. If we run:

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})

Reference: Link

Or

You can use Vuex state for that data property and define mutations only if you want to change the value.

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

Comments

1

If you're already using Vuex, simply set your data into the store's state and don't provide any mutations to keep it read-only.

For example...

const store = new Vuex.Store({
  state: myObject
})

// assuming you've added Vue.use(Vuex) if using a module system
new Vue({
  // el, data, etc
  store
})

then your Vue instance or components can access

this.$store.state.somePropertyOfMyObject

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.