Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access a variable inside an array in Vue JS

Javascript and Vue beginner here. Trying out examples to learn the basic concepts.

<template>
  /*<p v-bind:class="['bold', 'italic', isValid ? 'valid' : 'invalid']">*/

  <p v-bind:class="classArray">
    Hello, {{name[0]}} {{name[1]}}
  </p>
</template>

<script>

export default {
  data() {
    return {     
      isValid: true,
      name: ['John','Doe'],
      classArray: ['bold', 'italic', isValid ? 'valid' : 'invalid']
      
    }
  }
}
</script>

<style>
  .bold    { font-weight: bolder }
  .italic  { font-style:  italic }
  .valid   { color: forestgreen  }
  .invalid { color: crimson      }
</style>

Above code throws up the following error –

ERROR
[eslint]
/js/vue3/src/App.vue
16:38 error ‘isValid’ is not defined no-undef

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

✖ 1 problem (1 error, 0 warnings)

How do I access ‘isValid’ inside the classArray?

>Solution :

Define classArray as a getter that checks the current value of isValid of the object.

export default {
  data() {
    return {     
      isValid: true,
      name: ['John','Doe'],
      get classArray() { return ['bold', 'italic', this.isValid ? 'valid' : 'invalid']; }
      
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading