Passing boolean values to component attributes in Vue.js

I am attempting to create a straightforward input component using Vue, where if the condition IsPassword is true, the type will be set to "password," and if it is false, the type will be set to "text."
I suspect there may be a syntax error causing a parsing JavaScript error.

This is a simplified version of my code
App.vue

import InputText from "@/components/InputText.vue";

<template>
Username : <InputText/>
Password : <InputText :isPassword="true">
</template>

InputText.vue

<template>
<input :type="{IsPassword ? 'password':'text'}" value="I am encountering an error here"> 
</template>
<script>
export default {
    props: {
        IsPassword: Boolean
    }
}
</script>

Answer №1

To begin, ensure that the condition is enclosed in curly braces.

Next, the ternary operator should be structured like this:

condition ? action if true : action if false

Therefore, your code should appear as follows:

<input :type="IsPassword ? 'password' : 'text'" value="I am encountering an error here">

Answer №2

It may be necessary to include support for different types of features in the Input Text field.

To ensure a clean separation of concerns, I recommend keeping the logic outside of the templates:

import InputText from "@/components/InputText.vue";

<template>
Username : <InputText/>
Password : <InputText is-password>
</template>

<template>
   <input :type="inputType" > 
</template>

<script>
import {computed} from 'vue';

export default {
    props: {
        IsPassword: Boolean
    },
    setup(props){
       const inputType = computed(() => props.IsPassword ? 'password' : 'text')

      return{
         inputType
      }
    }

}
</script>

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 does Vue handle the situation when the value of an input field does not match the bound "data"?

Before diving into the intricacies of v-model, I want to take a closer look at how v-bind behaves. Let's analyze the example below: <div id="app"> <input type="text" :value="inputtedValue" @input ...

Steps for preventing a button from being enabled until all mandatory fields are completed

Is it possible to have a button disabled until all required fields are filled out, with the button appearing grey in a disabled state and changing color when all fields are completed? I am facing an issue where clicking on the previous button is causing ...

Creating a horizontal navigation bar using localscroll.js in your website is a great way

In my portfolio, I want to create a horizontal navigation with local scroll to showcase a gallery of various pictures. For this, I have a (div id="projects") with links structured like this: <div id="projects"> <ul id="content-slider-inside ...

Display a specific section of an image as the background in a div, with the image scaled and positioned perfectly

Utilizing a 1900 x 1080 image within a div as the background <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <style> html,body { height:100%; } #imageHolder{ ...

Encountering difficulties when attempting to run initial React Native app

Struggling with my journey of learning react-native, I encountered a roadblock while trying to run the application. Here is the error log. I'm hopeful for some assistance from anyone who can lend a hand. The development server returned response erro ...

Activate watch function upon Vue component mounting

Below is a vue component that I want to watch for triggering when it gets mounted. Can you guide me on how to achieve this? Vue.component('check-mark', { name: 'check-mark', template: `<input :value="value"/>`, pro ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

What is the best way to display the legend on my PieChart?

I am attempting to display the names of colors in my PieChart as a legend. Here is the JSON data: { "choice": "20-29 yrs. old", "count": 4 }, { "choice": "30-39 yrs. old", "count": 2 }, { "ch ...

Extracting data from websites: How to gather information from dynamic HTML elements

On the website I am exploring, there is a dynamic graph with descriptions below it that keep changing. My goal is to extract all these trajectory descriptions. The HTML code snippet related to the description area looks like this: <div class="trajDesc ...

Extracting information from a Postgres query in Node.js

I'm looking for guidance on how to pass the results of a postgres query in Node.js to another function. Can anyone provide an example? ...

What is the best method for using XMLhttpRequest in PHP to append options to a select element?

I'm looking to dynamically fetch values from a MySQL database using PHP and then add them as choices within a select element. Here is my HTML code: <label for='listDivision'>Division</label><select id='listDivision&apos ...

Troubleshooting problems with dynamic imported asset URLs in Vue and Vitest snapshot snapshots

After migrating my project from Vue-CLI & Jest to Vite & Vitest, I encountered a problem when trying to run tests through Jenkins. It seems that some snapshot images are failing to match due to discrepancies in asset paths. Expected : src="file:///C: ...

Exploring sections of a GLTF import within the primary rendering loop (apologies for any beginner questions)

As a Unity developer venturing into learning Three.js, I've come across a seemingly simple yet frustrating issue. My goal is to import and animate a 3D logo consisting of four separate meshes (elem1 to elem4) in my Three.js application. After exporti ...

formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is: vx = Math.floor(Math.random() * 20) vy = Math.floor(Math.random() * 20) Howev ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

Troubleshooting Vue.js 2: Difficulty with Vue locating files stored in the /assets directory (v-for loop)

My Vue-cli 3 project with Webpack has the following folder structure: /public /src /assets p1.jpg p2.jpg App.vue main.js I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

What is the process for disabling the CSS module feature in Next.js?

In Next.js, Global CSS can only be imported in _App.js. However, importing global CSS in every component is not allowed, so we have to use CSS modules to comply with this restriction imposed by Next.js. Currently, I am in the process of migrating a large ...