Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a component non-reactive data in Vue 2?

I have a categories array, which is loaded once (in created hook) and then it is static all the time. I render this array values in a component template.

<template>     <ul>         <li v-for="item in myArray">{{ item }}</li>     </ul> </template> 

My data property looks (it does not include myArray - I dont want reactive binding):

data() {     return {         someReactiveData: [1, 2, 3]     }; } 

My create hook:

created() {     // ...     this.myArray = ["value 1", "value 2"];     // ... } 

Problem is, that Vue throw error - I cant use myArray in a template, because this variable is not created when the DOM is created - mounted.

So how to do this? Or where can be stored component constants?

like image 674
Dave Avatar asked Aug 22 '17 09:08

Dave


People also ask

How do I make my Vue data not reactive?

To avoid the overhead, you can use Object. freeze to prevent Vue from making your objects reactive. The example freezes the attributes nested property, which means Vue won't pick up any changes in them. Other properties may change and we want those to be picked up by the reactive system.

How do you reset a Vue component?

To reset a component's initial data in Vue. js, we can create a function that returns the initial data. Then we can call the function to reset the data. to create the initialState function that returns an object with the initial data.

Are sets reactive in Vue?

We can use JavaScript maps and sets as reactive properties in Vue.


1 Answers

Vue sets all the properties in the data option to setters/getters to make them reactive. See Reactivity in depth

Since you want myArray to be static you can create it as a custom option which can be accessed using vm.$options

export default{     data() {         return{             someReactiveData: [1, 2, 3]         }     },     //custom option name myArray     myArray: null,     created() {         //access the custom option using $options         this.$options.myArray = ["value 1", "value 2"];     } } 

you can iterate over this custom options in your template as follows:

<template>     <ul>         <li v-for="item in $options.myArray">{{ item }}</li>     </ul> </template> 

Here is the fiddle

like image 183
Vamsi Krishna Avatar answered Sep 23 '22 23:09

Vamsi Krishna