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?
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.
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.
We can use JavaScript maps and sets as reactive properties in Vue.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With