M -
M -

Reputation: 28492

Do all imported arrays in Vue.js have to be reactive?

I'm importing a simple array of 4 strings called QUIZ_DATA into my Vue.js component:

["Question1?", "Question number 2?", "This is number 3!", "And # 4"]

These 4 questions are static and won't change. I don't need them to be reactive, so I import them into my component as QUIZ_DATA, but when I try to iterate through the array, it gives me an error that the property is non-reactive.

<template>
    <div v-for="(question, index) in QUIZ_DATA">
        {{ question }}
    </div>
</template>

<script>
import QUIZ_DATA from "~/plugins/QuizData.js";

export default {
    // Nothing here yet
}
</script>

The console says:

Make sure that this property is reactive.

I got rid of the error by copying the array into my component's data object, which feels like an unnecessary step, given that the array won't change:

data(){return {quizData: QUIZ_DATA}}

Is there a way of iterating through static objects without needing to copy them into the component's data() object first?

Upvotes: 2

Views: 101

Answers (3)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27222

Is there a way of iterating through static objects without needing to copy them into the component's data() object first ?

Answer is Yes, ways to achieve :

  • By using computed property.

const QUIZ_DATA = ["Question1?", "Question number 2?", "This is number 3!", "And # 4"];

new Vue({
  el: '#app',
  computed: {
    QUIZ_DATA() {
      return QUIZ_DATA
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(question, index) in QUIZ_DATA">
    {{ question }}
  </div>
</div>

  • As data is non-reactive we can use created hook.

let QUIZ_DATA = ["Question1?", "Question number 2?", "This is number 3!", "And # 4"];

new Vue({
  el: '#app',
  created: function () {
    this.QUIZ_DATA = QUIZ_DATA;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(question, index) in QUIZ_DATA">
    {{ question }}
  </div>
</div>

Upvotes: 0

Decade Moon
Decade Moon

Reputation: 34306

QUIZ_DATA must be a property of the component instance if you want to access it from within the template.

Non-reactive data can be assigned to the component instance in the created hook.

created() {
  this.QUIZ_DATA = QUIZ_DATA;
}

Upvotes: 3

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

You can return your array with computed property:

const QUIZ_DATA = ["Question1?", "Question number 2?", "This is number 3!", "And # 4"]
new Vue({
  el: '#demo',
  computed: {
    questions() {
      return QUIZ_DATA
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(question, index) in questions">
    {{ question }}
  </div>
</div>

Upvotes: 1

Related Questions