[英]Vue.js passing Boolean value to component attribute
I want to create a simple input component in Vue,我想在 Vue 中创建一个简单的输入组件,
which if the IsPassword
condition was true, set its type="password"
and if it is not, set it to type="text"
.如果IsPassword
条件为真,则设置其type="password"
,如果不是,则将其设置为type="text"
。
I'm probably making a mistake somewhere in the syntax because I'm getting parsing javascript error
我可能在语法的某个地方犯了错误,因为我正在parsing javascript error
this is Simplified version of my code这是我的代码的简化版本
App.vue App.vue
import InputText from "@/components/InputText.vue";
<template>
Username : <InputText/>
Password : <InputText :isPassword="true">
</template>
InputText.vue输入文本.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
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.