简体   繁体   中英

Vue.js passing Boolean value to component attribute

I want to create a simple input component in Vue,
which if the IsPassword condition was true, set its type="password" and if it is not, set it to type="text" .
I'm probably making a mistake somewhere in the syntax because I'm getting parsing javascript error

this is 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="Im getting error here"> 
</template>
<script>
export default {
    props: {
        IsPassword: Boolean
    }
}
</script>

First, you should set the condition in curly brackets.

Second, the ternary operator syntax should look like condition? if condition true: if condition false condition? if condition true: if condition false

So, it should look like

<input :type="IsPassword ? 'password' : 'text'" value="Im getting error here"> 

You will probably require to support feature types for the Input Text.

My suggestion is to keep logic outside 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM