How can multiple if loops for conditions be optimally rewritten in Vue/JS?

Within my Vue JS application, I have implemented code that changes the color of text based on a meter value. The code snippet looks like this:

<span class="card__form__meter__warning" :class=" { weak : password_weak, 'very-weak' : password_veryweak, strong : password_strong, valid : password_verystrong } ">{{ password_warning }}</span>

While the above code works, I believe it is overly repetitive and there must be a simpler way to achieve the same result:

data: {
                name: null,
                emailAddress: null,
                password: null,
                password_warning: 'Strong password required',
                password_veryweak: false,
                password_weak: false,
                password_strong: false,
                password_verystrong: false,
                ...
                    if (this.meter == 0) {
                        this.password_veryweak = false
                        this.password_warning = 'Strong password required'
                    }

                    if ( this.meter == 25) {
                        this.password_warning = 'Very weak (not strong enough)'
                        this.password_veryweak = true
                        this.password_weak = false
                        this.password_strong = false
                        this.password_verystrong = false
                    } 
                    if (this.meter == 50 ) {
                        this.password_warning = 'Weak (not strong enough)'
                        this.password_weak = true
                        this.password_veryweak = false
                        this.password_strong = false
                        this.password_verystrong = false
                    } 
                     if (this.meter == 75) { 
                        this.password_warning = 'Strong'
                        this.password_strong = true
                        this.password_verystrong = false
                        this.password_weak = false
                        this.password_veryweak = false
                    } 
                    if (this.meter > 75) {
                        this.password_warning = 'Very Strong'
                        this.password_verystrong = true
                        this.password_strong = false
                        this.password_weak = false
                        this.password_veryweak = false
                    }

I encountered difficulties when trying to remove previous conditional classes as the meter values changed, which led me to set the

this.password_weak = false
this.password_strong = false
this.password_verystrong = false

for each condition.

If you have any insights or suggestions, I would greatly appreciate your help.

Thank you!

-----edit-------

computed: {
                password_warning: function () {
                    if (this.meter == 0) {
                        this.password_class = ''
                        return 'Strong password required'
                    } else if (this.meter == 25) {
                        this.password_class = 'very-weak'
                        return 'Very weak (not strong enough)'
                    } else if (this.meter == 50) {
                        this.password_class = 'weak'
                        return  'weak (not strong enough)'
                    } else if (this.meter == 75) {
                        this.password_class = 'strong'
                        return 'Strong'
                    } else {
                        this.password_class = 'strong'
                        return 'Very strong' 
                    }
                },
            }

Answer №1

Avoid using conditional classes directly from an object literal. Instead, store your class name in a single data property and apply it directly:

<span class="card__form__meter__warning" :class="password_class">{{ password_warning }}</span>

This makes setting this.password_class much simpler.

I suggest making both password_class and password_warning computed properties that depend on the meter value, rather than setting them imperatively.

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

How is it possible for the javascript condition to be executed even when it is false?

Despite the condition being false, the javascript flow enters the if condition. Check out the code snippet below: <script> $(document).ready(function() { var checkCon = "teststr2"; console.log("checkCon: "+checkCon); if(checkCon == " ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...

Encountered an Uncaught TypeError in VueJS 3 + Laravel: Unable to access the property 'component' as it is undefined

Greetings everyone, I am encountering a minor issue while trying to initiate Vue on my Laravel project. Below is my package.json configuration: "devDependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.32", ...

Optimizing AngularJS ui-router to maintain state in the background

Currently working on an AngularJS project that involves a state loading a view containing a flash object. I am looking for a way to ensure that the flash object remains loaded in the background during state changes, preventing it from having to reload ev ...

Consider using React Components as an alternative to implementing pagination dots within Swiperjs, as it may help resolve the issue displaying

I seem to be encountering a small issue and I believe I am making a mistake somewhere. How can I replace the default dots with custom elements for pagination in Swiperjs for React? The custom element should return an SVG from an array of icons. Initially ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

The Javafx WebEngine's executescript() function is unable to send a multiline string

Issue: I'm struggling to make the JavaFX WebEngine trigger a JavaScript function when using a Java String object with multiple lines. If I input the following example in HTML: "asd" ENTER "qwe" into the textArea, and then click the send button, the f ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

How is it that when a function is called with just one parameter, it ends up receiving the entire element?

In my table, I have various item numbers listed with corresponding quantity input fields identified by id="itemNumber". Each line also includes a button that triggers a function (onclick="addItemAndQuantity(itemNumber)") to retrieve inf ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Is there a way to use Javascript to launch a new page on my website?

I'll do my best to provide a clear explanation of what I need. Take a look at this: My website is filled with a plethora of news articles, all retrieved from the MySQL database using select * from table_name. Displaying so much news on one page can ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Tips on implementing VueStripe in a vue2 Project

I recently integrated Vue Stripe into my vue2 Project and encountered 2 similar errors in my code : Property 'redirectToCheckout' does not exist on type 'Vue | Element | (Vue | Element)[]'. Property 'publishableKey' does ...

Getting a Next.js error after performing a hard refresh on a page that contains a dynamic query

I have encountered an issue with my Next.js app when I attempt to hard reload it in production mode. The error message I receive is 404 - File or directory not found. Below is the code snippet I am using: import { useRouter } from "next/router"; import ...

Ways to retrieve the current state within a function after invoking the setState method

I'm currently working on a function to store the blogPost object in a document within my Firestore database. The process I have in mind is as follows: Click on the SAVE button and initiate the savePost() function The savePost() function should then ...

Tips for Resolving the Problem with React Hook Closures

import React, { useState } from "react"; import ReactDOM from "react-dom"; function App() { const [count, setCount] = useState(0); function handleAlertClick() { return (setTimeout(() => { alert("You clicked on: & ...

Is it possible to execute a function defined within an eval() function using setInterval()?

const evaluation = eval(document.getElementById("codearea").value); setInterval(evaluation, 10); I am seeking a way to access a function that is declared within the eval function, for example: setInterval(evaluation.examplefunc, 10) I attempted ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...