Tips on how to retrieve a variable from an array in Vue JS

New to Javascript and Vue, I am exploring examples to grasp the fundamental 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>

The code above triggers 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 can I access 'isValid' within the classArray?

Answer №1

Perhaps consider implementing a computed property called `classArray` to ensure it accurately references the `isValid` data attribute within the component. Give it a try!

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

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

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

Answer №2

To create a getter called classArray, define it to evaluate the current value of isValid within the object.

export default {
  data() {
    return {     
      isValid: true,
      name: ['Alice','Smith'],
      get classArray() { return ['highlight', 'underline', this.isValid ? 'valid' : 'invalid']; }
      
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Combining various FormGroup types into a single object type in Angular 5

I am currently utilizing the mat-stepper feature from the Angular Material design library. Within my application, I am using 3 separate FormGroups to gather information and send it to a database using the httpClient method. To achieve this, I have defined ...

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

Web application error: Karma and Webpack cannot locate Angular controller

After following a blog post on setting up an Angular project with webpack, I used an associated boilerplate on Github. Although the app is functioning properly, Karma seems to have trouble finding the controller it needs to test. // karma.config.js modul ...

Is there a new update to Google Maps API?

After successfully building a map component for a web application using google maps, open layers, and the dojo toolkit, it suddenly stopped loading earlier this morning. Even though there are no JavaScript errors and open layers and Google still initialize ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

Utilizing AJAX to fetch and retrieve a JSON array

Check out the javascript code below: var formSerializedData = $('form#registration-form').serialize(); $.post( '<?php echo $this->url('/register', 'do_register')?>', function(response) { alert(response); } ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

Challenges with optimization in AngularJS and Angular Material

Currently, I am working on an AngularJS application that utilizes 7 Angular Material tabs. One issue I have encountered is a significant amount of animation lag when switching tabs or opening a md-select element. According to Chrome Developer Tools, the fr ...

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

What is the proper method for activating the lights in a traffic light sequence?

I've been working on creating a traffic light sequence where each time the "change lights" button is pressed, the light is supposed to change. However, I'm facing an issue where the code only displays the red light and doesn't switch to ambe ...

Obtaining the IP address of the client's request

In an effort to prevent others from wasting time in the future, I am sharing this post even though it's not really a question anymore. Objective: Obtain the client IP address and set specific values based on certain octets in the IP address. While w ...

Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two sep ...

Having trouble importing images in React and passing them as a prop?

I'm attempting to import images, place them into an array, and then pass that array to a prop in a component to display different images. However, after passing the array to the component, the items accessed from the array are showing as undefined, pr ...

Adjust the width of the dropdown menu for the v-combobox

I am currently working on creating a multiple search filter similar to the one found in Gitlab dashboard. https://i.sstatic.net/YHivl.png For this task, I am utilizing Vuetify's v-combobox like this : <v-combobox id="mycombo&quo ...

Enhance the size of dynamically generated svg elements by scrolling the mouse wheel in and out

In my ASP.NET application, I have a view page where SVG elements are dynamically generated. Now, I want to implement zoom functionality for all the created SVG elements. Zooming in should occur when scrolling up and zooming out when scrolling down. <sv ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...