I have the following code:
<input type="text"
@input="disableField($event.target)"
:disabled="isFieldDisabled(????)"
/>
I want to pass to the isFieldDisabled method the same value which I get in $event.target - the element reference. I cannot find the way how to do this. I know that I could use the :ref but in this case I need to do it as shown above.
This is only the example use case. I know that to disable the field I can do it better but I want to show the problem in simplest way.
CodePudding user response:
Create a property in Vue data.Bind the input to a v-model
to that data property.
In your script:
data : {
/// other values ....
inputValue: '' // add this field to bind to input
}
Use that property in your method isFieldDisabled(inputValue)
<input type="text"
@input="disableField($event.target)"
v-model="inputValue"
:disabled="isFieldDisabled(inputValue)"
/>
CodePudding user response:
This isn't possible the way you're asking for it.
- The way that Vue works with VNodes, the element won't exist the first time you try to evaluate
disabled
: Vue evaluates the properties to determine how the DOM should look and then creates the elements to match. As here:Note that you can only access the ref after the component is mounted. If you try to access
input
in a template expression, it will benull
on the first render. This is because the element doesn't exist until after the first render! - With async components, the attributes will need to have well-defined values even if there isn't a Component to render yet, let alone well-defined elements to position there.
- With fragment components, there won't ever be a single HTML element to interact with, because the component represents multiple top-level HTML elements.
Events don't have to play by the same rules, because you're defining handlers: DOM events will come from one source and apply to one target, and absent components don't emit events. Even then, the syntax gives you access to $event
, not to an $el
for a direct element reference.
The most straightforward way is to use a ref
to get to the object after Vue creates it, subject to the same null-on-first-render ref
rules above. If you need to pass a handle into a multipurpose method in the shape of getFoo(argument)
your argument may have to be a string or enum key you define, not the element itself.