WoJ
WoJ

Reputation: 30074

Where to declare non-changing data?

I would like, in a Vue component, to use some data that does not change. The following code does not work:

const numbers = [1, 2, 3]
new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="number in numbers">
    {{number}}
  </div>
</div>

It fails with the error

[Vue warn]: Property or method "numbers" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

The messages indicates that I tried to use numbers in a "reactive" way. In my case, however, the data is expected not to change (highlighted by the const declaration).

I can of course push numbers into the instance, and this works:

new Vue({
  el: "#app",
  data: {
    numbers: [1, 2, 3]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="number in numbers">
    {{number}}
  </div>
</div>

I feel however a bit uncomfortable with this, my understanding of "reactive" being that data is a place for information that changes (and the change is reflected in the DOM).

What is the correct way to use constant (non-changing) data in Vue? (specifically where to declare it)

Upvotes: 0

Views: 114

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37963

  1. All data the template need to access has to be on Vue instance (data or computed) (you can imagine every access in template is prepend with this.) and there is no way around it
  2. Making you data part of Vue instance make it reactive. Usually its not a problem but it might in case you have huge amount of data you know will never change (perf). In which case you can use a tip from the docs and apply Object.freeze() which makes whole object "non-reactive" but also unable to change in any way
  3. You can fine-tune the data using this tip from Akryum (Vue core member) to create objects with some properties reactive and some non-reactive (Applies only to Vue2 which uses Object.defineProperty to make data reactive. I'll try to update for Vue3 proxies later..)

Option 2. is probably best approach for your use case...

Upvotes: 1

Related Questions