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

Time:02-26

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?

CodePudding user response:

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;
}

CodePudding user response:

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>

  • Related