Using V-bind to assign multiple classes has never been easier

Is there a way to assign one of two classes to an element based on three possible input variables in my Vue.js code?

<input type='text' class='inputwordtext' v-bind:class="{(wordupload.firstchoice.selected == 'Zinnenlijst') : wordlongwidth, (wordupload.firstchoice.selected != 'Zinnenlijst') : wordshortwidth}">

I want the element to have the class "wordlongwidth" if wordupload.firstchoice.selected is equal to Zinnenlijst. Otherwise, it should have the class "wordshortwidth". How can I achieve this?

Answer №1

If you want to achieve this with just one line of code, you can use a ternary operator like this:

<input 
  type='text' 
  class='inputwordtext'
  :class="wordupload.firstchoice.selected === 'Zinnenlijst' ? 'wordlongwidth' : 'wordshortwidth'"
>

However, for better readability, it is recommended to create a computed property:

computed: {
  inputClass() {
    let selected = this.wordupload.firstchoice.selected;
    return (selected === 'Zinnenlijst') ? 'wordlongwidth' : 'wordshortwidth';
  }
}

Then simply reference the computed property in your template:

<input type='text' class='inputwordtext' :class="inputClass">

Answer №2

In the documentation for vue.js, it is recommended to use a ternary expression and combine v-bind:class with your regular class in the following way:

<input type='text' :class="[wordupload.firstchoice.selected === 'Zinnenlijst' ? 'wordlongwidth' : 'wordshortwidth', 'inputwordtext']">

To find more information about class binds, refer to the vue.js documentation here:

https://v2.vuejs.org/v2/guide/class-and-style.html#Array-Syntax

If you want to learn more about ternary expressions, check out this resource:

https://www.w3schools.com/js/js_comparisons.asp

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 results are positive in Postman, however, the browser does not display the same success

My website has a form that uses the v-model directive for data binding. It serves as a default login page. However, when attempting to log in, I receive a 401 unauthorized error. Interestingly, when testing the same credentials using Postman, I am able t ...

Strategies for extracting taginput information from an API

I have a collection of tags stored in a database that I can retrieve using an API. Although I am able to use these tags within my template, I am facing issues specifically when trying to display them in the tag list. As someone who is new to Vue.js, I sus ...

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

exploring XML documents

With around 250,000 XML files, each named with a UUID, I am looking for the most effective way to perform a full text search on these files and identify the UUID of the matching ones. What would be the optimal approach for indexing them in a nodejs environ ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

Function in head not triggering on OnMouseOver event

My goal is to have specific text display on my page when a user hovers over an image, with the text changing for each image. Below is the code snippet for the header section: <head> <title>Indian Spices Page</title> <link rel="s ...

How can I convert a string containing integers into an int[] using javascript or jQuery?

I want to create a feature that allows users to input a list of IDs in a textarea, with the option to separate them by either whitespace or commas. After the user inputs the list, I need to convert it into an int[] array but also throw an error if the str ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Create a custom style for Vue2-Google-Maps autocomplete feature that mirrors the sleek design of Vuetify

Is there a simple way to style the gmap-autocomplete field to resemble a vuetify v-text-field? I've tried using the Vuetify-google-autocomplete module, but it's causing more errors than expected. What is the most straightforward method to make & ...

`Changing the output of a jQuery .load function`

I've created a webpage that pulls content from an article, but I'm looking to display only the first 100 words of the article. Currently, my page successfully loads the article using this code: $(function(){ $('#startOfArticle').l ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Trying to dynamically filter table cells in real time using HTML and jQuery

During my search on Stack Overflow, I successfully implemented a real-time row filtering feature. However, I now require more specificity in my filtering process. Currently, the code I am using is as follows: HTML: <input type="text" id="search" place ...

What steps should I take to ensure a local HTML page retains the current section that is hidden open whenever it is reloaded?

One of the challenges I have encountered with my local HTML note-taking file is that, despite dividing it into hidden sections accessible by clicking on buttons at the top of the page, reloading the content resets it back to its default state. This means t ...

Retrieving the output from a nested function within a function in a Node.js application connected to a

I'm currently working on a basic web application that interacts with a database by performing INSERT and SELECT operations on a single table. While I have utilized a function from various tutorials, I am struggling to retrieve the results from the SEL ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

Configuring bitfinex-api-node with Node.js to efficiently handle data from the websocket connection

Apologies for the vague title of this question, as I am not well-versed in programming and even less so in node.js My goal is simple: I aim to utilize the bitfinex-api-node package (a node.js wrapper for the bitfinex cryptocurrency exchange) that I instal ...