Reputation: 30074
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
Reputation: 37963
data
or computed
) (you can imagine every access in template is prepend with this.
) and there is no way around itObject.freeze()
which makes whole object "non-reactive" but also unable to change in any wayObject.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