Do class bindings with variables need to be inline when using Vue 3?

Consider the following HTML:

<template v-for="(child, index) in group">
    <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}">
        <div>Container Content</div>
    </div>
</template>

Is there a method to externalize the class binding from the HTML while still relying on a condition passed via the v-for loop (child.id)?

Although the documentation mentions the possibility of binding computed properties, it seems that they do not accept arguments. I have attempted this approach without success.

Answer №1

One way to handle this is by creating a method and passing the item as an argument:

<div :class="classes(child)">
setup() {
  ...
  const classes = (child) => {
    return {
      'border-pink-700 bg-gray-100': selected.value === child.id
    }
  } 
    
  return {
    ...
    selected,
    classes
  }
}

If you are working with Vue 2 or the Options API, you can achieve this like so:

methods: {
  classes(child) {
    return {
      'border-pink-700 bg-gray-100': this.selected === child.id
    }
  }
}

Just remember not to modify instance properties within the method, but it's okay to read them.

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

What are the steps for positioning tables using HTML?

As a newcomer to this field (literally just started two days ago), I have managed to generate tables from an XML file using my XSL file. However, aligning these tables properly has become a bit of a challenge. I initially used the align attribute of <ta ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...

What is the best way to retrieve JSON values based on a key using JavaScript, jQuery, or AngularJS?

Here is some JSON data that I need help with: var jsonData = { "title": "Testing", "settings": { "mySettings": false }, "jsonList": ["TestingList"], "testJsonVals": { "Test1": { "name": "name1", ...

Issue with Titanium: Unable to scroll within tableview

The tableview is not scrolling as expected. I tested it on a mobile device and the scrolling worked fine, but it doesn't seem to work on tablets. Please assist. CODE var win = Titanium.UI.createWindow({ title : 'Medall app', back ...

Ways to identify the moment jQuery datatable is initialized and populated with information

I am currently using the most recent version of jQuery datatables. I'm curious if there is a callback function available that triggers right after the data has been loaded and displayed in the table? While experimenting with a datatable in IE8, I hav ...

How can I trigger a masterpage function from a contentpage in asp.net?

I am trying to call a function on the masterpage from a content page in the codebehind. Here is my attempt: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert__", string.Format("setStatusBarMessage('{0}',{1});", barMessage, ty ...

Updating the state of a React component through a button click using React-JS

In my React-JS project, I am using Semantic-ui to create form inputs and a submit button. These forms have a property called 'error', and the value of this property is determined by the state. The issue arises when I click on the 'Next&apos ...

Navigating the missing "length" property when dealing with partial functions generated using lodash's partialRight

I've been utilizing MomentTimezone for time manipulation within the browser. My development stack includes TypeScript and Lodash. In my application, there is an accountTimezone variable set on the window object which stores the user's preferred ...

JavaScript: Filtering list by elements that contain a certain value

I have the following collection of objects: [ { employeeId:1 employeeName:"ABC" }, { employeeId:2 employeeName:"ABD" }, { employeeId:3 employeeName:"FEW" }, { employeeId:4 employeeName:"JKABL" },] I am looki ...

Every time I try to install npm, I am bombarded with a massive error log

I recently downloaded the Vue Black Dashboard from this GitHub repository (https://github.com/creativetimofficial/vue-black-dashboard), but when I tried running npm install, I encountered a lengthy error log that left me confused. For context, I am operat ...

An error has occurred in Angular5 and Three.js: 'Scene1' property is undefined

Running into an issue with my angular5 website integrated with Three.js. I keep getting an error message that says: Cannot read property 'Scene1' of undefined when trying to add an object to the Scene. Any suggestions on how to properly define th ...

Altering the dimensions of Bootstrap's default navbar for a more compact look

Currently, I am attempting to modify the size of Twitter Bootstrap's standard navbar to a smaller dimension. My goal is to have the Brand/logo on the left side, menu options in the center, and social media icons on the right side within the navbar. U ...

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Strategies for halting the return of a JavaScript function until all AJAX requests have been completed

function processData(data) { //perform some data processing return data; } function test() { $.ajax({ 'url': api1, 'data': { 'use': "200" }, 'dataType': ' ...

Creating ellipses using Three.js with a specified list of points

Currently, I am working on a solar system model using Three.js. I have a function that calculates the position of the planet based on the day, but I am struggling to draw the correct elliptical orbit for the planet using a list of points generated from tha ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

Learn the steps to update PHP headers on a specific website using AJAX

contactfrm.php <?php // Server side validation $name = $_POST['name']; $surname = $_POST['surname']; $bsubject = $_POST['subject']; $email= $_POST['email']; $message= $_POST['message']; $to = " ...

Shifting gradient hues for illustrations?

One technique I have mastered is creating dynamic gradient colors for text elements using the following CSS: a { &:hover { background: linear-gradient(-45deg, green, yellow, red, blue); background-size: 200% 200%; animation: gradient-movi ...