Enhancing a Vue component by including two dynamically computed class properties within a :class="{{}} {{}}" tag

As a newcomer to the Vue world, I have been experimenting with applying 2 computed properties to a :class attribute. Initially, I tried separating each property by a space like this: :class="{{prop1}} {{prop2}}", but upon reload, all content would disappear due to an error in my approach.

I am wondering if anyone can confirm whether this is achievable or advisable?

Context

My objective is to create an input field that will display based on

:class="{{showWhenButtonClicked}}"
. Additionally, I aim to assign either a green or red input class name depending on the validity of the email provided.

If there are any crucial details I may be overlooking or a more efficient method of achieving this, I would greatly appreciate any insights. Thank you!

computed: {
  validateEmail() {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(this.emailTo).toLowerCase())
  },
  showEmailInput() {
    return this.sendEmail ? 'hide-show-option' : 'hide-option-input'
  },
  displayEmailError() {
    return this.validateEmail() ? "valid-input" : "not-valid-input"
  }
},

<input :class="{{showEmailInput}} {{displayEmailError}}" placeholder="Enter Email..." v-model="emailTo" @blur="{{validateEmail}}" type="email">

Answer №1

To apply multiple classes from an array, you can utilize the array syntax:

<input :class="[showEmailInput, displayEmailError]"/>

Answer №2

Out of all the responses, Nick's answer stands out as the most impressive. However, there is another way to streamline the code by storing the class in a computed variable:

  classList({ sendEmail, validateEmail }) {
    return [
      sendEmail ? 'hide-show-option' : 'hide-option-input',
      validateEmail ? "valid-input" : "not-valid-input"
    ]
  }

Alternatively, you could opt for returning an object instead, although it may not be as concise as using an array:

  classObject({ sendEmail, validateEmail }) {
    return {
      'hide-show-option': sendEmail, 
      'hide-option-input': !sendEmail,
      'valid-input': validateEmail,
      'not-valid-input': !validateEmail
    }
  }

As your code becomes more intricate and requires complex logic for classes, both of the options mentioned above will prove to be even more beneficial.

Answer №3

Give this a shot

:class="item1 + ' ' + item2"

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

Leverage the power of Vuejs to create a seamless user experience with one tab dedicated to control

Thinking about developing an App using vuejs for showcasing photos, I am interested in segregating the view container from the photo control by either a new tab or a separate browser instance. How should I kickstart a project like this? Should I opt for tw ...

Adjusting the screen width to activate a responsive nav bar with a centered title

I'm facing an issue with the alignment of the heading within a navigation bar, causing the links to wrap before the collapse of the nav-bar occurs - https://i.sstatic.net/bKyPM.png I am trying to make the links collapse earlier than they currently d ...

Launching the development server on a project created using Vue CLI 3

After successfully installing Vue CLI 3 globally on my Windows system using the command npm i -g @vue/cli, I proceeded to generate a project with the command vue create vue-project. I made sure to select all the necessary plugins as prompted during the se ...

What is the best way to nest one button inside another button in Vue?

Currently, I am facing an issue with nesting one button inside another, as it is not allowed. However, I am using Bootstrap and applying the "btn ..." class to a span to make it look like a button. The desired look of my button is: Filename.jpg <sm ...

Achieving a display of 4 images side by side in CSS without generating a horizontal scroll bar

Currently, I'm tackling a project (which entails utilizing HTML and CSS) that requires 4 images to be displayed in a row and scale accordingly to the user's screen width in order to avoid any overlapping issues. My attempt to resolve this using ...

Vue is having trouble loading dynamic src files, and the require function isn't functioning properly

I'm facing an issue with displaying a dynamic image. When I use the following code: <img :src="src" alt="img"> It doesn't seem to work. However, it works perfectly fine when I use: <img src="../assets/img/banana ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

What are the best practices for preventing risky assignments between Ref<string> and Ref<string | undefined>?

Is there a way in Typescript to prevent assigning a Ref<string> to Ref<string | undefined> when using Vue's ref function to create typed Ref objects? Example When trying to assign undefined to a Ref<string>, an error is expected: co ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

Tips for ensuring the footer always stays at the bottom of the page

I'm having an issue with keeping the footer pinned to the bottom of the page. I haven't applied any specific styles to the footer, just placed it at the end of the content. Everything looks great until there's a page with minimal content, ca ...

Exploring Nuxt's speed and efficiency with Lighthouse

Despite having simple code, I am puzzled by the low performance of my Nuxt web app in Lighthouse. You can check out my Nuxt web app deployed under the name hadicodes.com online. Here is a snippet from my nuxt.config: // Your nuxt.config settings here Th ...

Increase the space below the footer on the Facebook page to allow for an

I recently created a webpage at and noticed that it is adding extra height below the footer on my Facebook page: "" I am seeking assistance on how to remove this additional 21px height below all content in the footer. I have tried various templates but n ...

obtain the image number by extracting a portion of the text

How can I extract the image number from a string using the sub-string function? I have applied the sub-string function to the property below. It returns 3 at the end in Chrome, but it does not work properly in Mozilla. Issue : After "-->", when I chec ...

Load CSS styles once the HTML content has been generated by the PHP script

One way to dynamically add a section of HTML during page load is by making use of PHP in the index.php file: In your index.php file, you can include a section like this: <html> <head> <link href="css/style.css" rel="stylesheet"> ...

Can a piece of code be created that generates the XPath for a specific element?

I'm interested in finding out if there is a way to automatically generate an XPath by simply selecting an element, eliminating the need for manual updates when changes occur in HTML files on websites. I welcome any suggestions or alternatives that can ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

Is it possible to add a class to the parent element when the input value of a sub-child element is

Is there a way to select and add a class to an li element in which the sub-child input is empty when clicking on button #btn-modal-clear? If so, what is the best approach to achieve this? Example HTML Code: <li>...<li> <li> <a c ...

What is the best way to showcase results in a Laravel controller using a Vue template?

Good day, I am currently facing a challenge with displaying return values from an array in a Laravel Controller on a Vue Template. Any assistance would be greatly appreciated. public function search(Request $request) { $batchResults = &bsol ...

Is there a way to apply a css class to all nested elements in Angular 6 using Ngx Bootstrap?

I've defined a CSS class as follows: .panel-mobile-navs > ul > li { width:100% } Within the HTML, I am utilizing Ngx-bootstrap for a series of tabs like this: <tabset class="panel-mobile-navs" > ... </tabset> My intention is to ...

BufferGeometry in three.js not displaying as expected

This is my first question for a project using three.js. I hope it's not too simple, as I have already done some research without success so far. I am currently creating a Line2 and need to control the thickness of the line. Initially, I followed this ...