Search code examples
javascriptvue.jsvuejs3

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

✖ 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']; }
          
        }
      }
    }