vue - When using v-bind:class, how can you interact with a nested computed property object value?

Looking to assign a class to an inbox item in Vue when the value is equal to 'null'. I have almost achieved this, but there's one aspect I can't figure out. I've been following examples like https://v2.vuejs.org/v2/guide/class-and-style.html, but I have some specific requirements. I need to dynamically define a class based on the computed property value nested within my form. I have a form with multiple input fields (generated using v-for), and I should check each field's value and apply a specific class if certain conditions are met. I can achieve this initially, but struggling to update the class as the user changes the input values.

This is an example of the loop:

<div
  class="form__field form__field--autocomplete"
  v-for="input in info"
  :key="input.PARAMETER_NAME"
  v-if="input.PARAMETER_NAME != 'p_euser' && input.PARAMETER_NAME != 'p_dbuser_password'"
>

Here is an example of one particular field type based on the input.DATA_TYPE:

<input
    v-else-if="input.DATA_TYPE == 'smallint' || input.DATA_TYPE == 'int'"
    v-model="recordComputed[input.PARAMETER_NAME]"
    type="number"
    class="form__field-input"
    v-bind:class="['', { 'nullclass' : [recordComputed[input.PARAMETER_NAME=='null']] }]"
    :disabled="input.i2_primary_key == '1' && method == 'edit'"
  >

The recordComputed object is the main object (computed property) defined like this:

  recordComputed: {
   get () {
    let record = this.record
    this.info.forEach((input) => {
      var parValue = this.selected[input.i2_header_db]

      // if we do not have parValue and it is typeof=='object', we set it as null
      if (!parValue && typeof (parValue) === 'object') {
        parValue = 'null'
      }
      record[input.PARAMETER_NAME] = parValue
    })
    return record
  },

My question is whether it's possible to read the value from a computed property reactively – specifically, one of its keys – in order to dynamically change the class for a specific input field. If there are alternative approaches, I'm open to suggestions.

Answer №1

It is entirely possible...

<template>
  <div>
    <div v-for="input in inputs" :key="input.id">
      <input type="text" :class="{ active : getIsActive[input.id - 1] }" :value="input.name">
    </div>
    <input type="checkbox" v-model="odd"> Odd ?
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      inputs: [
        { name: "input 1", id: 1 },
        { name: "input 2", id: 2 },
        { name: "input 3", id: 3 },
        { name: "input 4", id: 4 }
      ],
      odd: false
    };
  },
  computed: {
    getIsActive() {
      return this.inputs.map(item => item.id % 2 === (this.odd ? 1 : 0));
    }
  }
};
</script>

<style scoped>
.active {
  background-color: #42b983;
}

input {
  margin: 10px;
}
</style>

Your class binding appears unusual

v-bind:class="['', { 'nullclass' : [recordComputed[input.PARAMETER_NAME=='null']] }]"

Why are you using input.PARAMETER_NAME=='null' as an index into the computed property? Also, there are too many square brackets. And using 'null' is quite strange, why not just use null?

Perhaps it should be like this?

v-bind:class="{ 'nullclass' : recordComputed[input.PARAMETER_NAME]==='null' }"

Answer №2

I devised a somewhat unconventional solution. Instead of simply evaluating against the value of a field, which is only effective for an initial assessment, I opted to create a new property called isNullText. Within a method named checkForNulls, I assigned true or false to this property based on the value of the recordComputed property. Here are the key components that helped me resolve the issue:

data() {
    return {
        isNullText:[]
    }
}

Next, within the methods section:

methods: {
    checkForNulls () {
        for (let [key, value] of Object.entries(this.recordComputed)) {
            console.log(
${key}: ${value}
)
            if (value === 'null') {
                this.isNullText[key] = true
            } else {
                this.isNullText[key] = false
            }
        }
    }
}

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

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Only implement the CSS styles if there are multiple elements that have the same class

I have 2 cards with the class card displayed within a card-stack. There can be any number of such cards. <div class="card-stack"> <div class="clear"><button name="clear" value="Clear all" onclick=&qu ...

Is there a workaround using jQuery to enable CSS3 functionality across all browsers?

Is there a way in jQuery to make all browsers act as if they have CSS3 capabilities? ...

Basic Timer with Visual Background

Struggling to find the right CSS/script for a straightforward countdown timer, Here are the requirements: Countdown in days only, no need for hours, minutes, and seconds Ability to use a custom image as background I've scoured online searches but n ...

php executing javascript - error

I have a question regarding my PHP file code: echo '<script type="text/javascript">'; echo '<audio id="player" src="../cdh/ba1.mp3"></audio>'; echo '<a onclick="document.getElementById( ...

Execute JavaScript function with a delay once the webpage has finished loading

I am currently working on a basic function that runs when the page is loaded. However, even though the page has finished loading, there are times when it takes about half a second for the content to actually appear. While this typically wouldn't be an ...

Looking for an easy solution in RegExp - how to locate the keys?

Similar Inquiries: Retrieving query string values using JavaScript Utilizing URL parameters in Javascript I am tasked with extracting specific keys from a series of URLs where the key is denoted by 'KEY=123'. My goal is to identify and e ...

Error in electron-builder: Module 'dmg-license' was not found

Seeking a straightforward method to create an electron app for macOS from a Linux machine. Unfortunately, the electron-builder -m command is not functioning properly. Here is the complete output of the command: electron-builder -m • elec ...

What are some techniques for applying masking to various elements beyond just input fields within React?

I am currently developing an admin dashboard using NextJS and MaterialUI (mui), and I am facing a challenge with masking certain values, such as phone numbers, that are retrieved from the backend without any masking applied. While I have successfully impl ...

Using Javascript to convert an SVG file into DOM elements

Seeking assistance with uploading an SVG file and then inspecting or parsing it to utilize the elements and values within the DOM. After extensive searches, I've only found information on parsing from the DOM itself. Is this task feasible? If so, cou ...

Preserve file sequence with jquery file upload

I recently came across an interesting upload script at the following link: This script utilizes jquery file upload to allow for uploading multiple files simultaneously. I'm curious about how to transmit the order in which the files were selected to t ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...

Encountering an error while populating the Google Charts API with data: "The column header row need to be in array format."

Is there a way to populate a Google Chart with data from a function? I'm encountering an issue where I define the header row but receive an error message saying "Column header row must be an array." How can I resolve this problem? Below is the code sn ...

Choosing the right CSS selectors for elements within other elements

I'm trying to add a stagger effect to the fade-in animations of images within a gallery. After looking over my code, I believe the issue lies in how I am setting the animation-delay in the CSS selector. I am not sure if SCSS is supported in this snipp ...

Utilize Apollo to retrieve a variety of queries at once

Currently, I'm utilizing nextJS for my frontend development along with Apollo and GraphQL. For fetching queries, I am using the getStaticProps() function. To enhance modularity and maintainability, I have segmented my queries into multiple parts. The ...

What is the method for accessing HTML tag data within a script?

Looking for a way to extract a specific substring from a given string: var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`; Is there a method to extract the following substring? 'Enter a valid email ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

Converting a JavaScript dictionary into an array of documents: The ultimate guide

I have an object that looks like this: const obj = { "restaurant": 20, "hotel": 40, "travel": 60 } Is there a way to transform it into the format below? const newArray = [ { "category_name": "restaurant", "amount": 20 }, { "category_na ...

How to Toggle Div Visibility with AngularJS ng-show and ng-click

In order to eliminate error messages, I decided to clear the field with a button click. This approach successfully removed the error in my initial test. <div class="errorPopup" data-ng-click="runner.Name = null" data-ng-show="mainForm.name.$error.pat ...

How to count the keys of an object in JavaScript that use dot notation?

Looking to tally the arrays within a javascript object. This feedback is returned from Laravel validator. { "message":"The provided data was invalid.", "errors":{ "roomtype_id":[ "Please choose a room type" ], "pri ...