-3

I'm creating an input component and I want to pass a required property in, based on a boolean from the parent component

#Parent component
<Input 
   :required="false"
/>
#Child component
<input 
     @input="event => $emit('update:value', event.target.value)"
     :required="required" 
/> 

The problem is, when the required from the parent component is false, it still puts required into the html (which the browser reads as required).

How can I achieve this?

Thanks Mark

Mark
  • 70
  • 3
  • 13

2 Answers2

1

For VueJs 2 or earlier version you can use

<input :required="test ? true : false">

in VueJs 3 you have to use the null to prevent the rendering of the attribute in html tag.

 <input :required="test ? true : null">

VueJS conditionally add an attribute for an element

Parth Patel
  • 119
  • 1
  • 5
0

You should explain more. I provide a situation as you describe in stackblitz where I link it here. It works and it is a simple form with submit when you change the required value in App.vue you could see the input element in HelloWorld.vue is changing in the inspector. Hope you find it usefull.

ghazal khaki
  • 634
  • 3
  • 9
  • Hi Ghazai. Thank you for the stackblitz. The problem with that is, if required is false, there is no input box. – Mark Dec 09 '21 at 10:12
  • Sorry, I was testing something else on it and now removed additional `v-if`. it's working now. – ghazal khaki Dec 09 '21 at 10:18
  • Did you check it? Does it work? – ghazal khaki Dec 09 '21 at 11:19
  • Yeah. If you set it to false and inspect the element of the input you'll see it says , which is correct, but from a browser validation point of view, it thinks required is set – Mark Dec 09 '21 at 15:31
  • It's weird because I'm checking the element in the chrome inspector and it doesn't have any attribute when value is set to false and so it doesn't check the validation of required. what browser are you checking in? – ghazal khaki Dec 09 '21 at 15:41