$refs should be reactive to be able to use them in computed properties
See original GitHub issueNow that refs are no longer reactive, we need to emit events and payloads from child components. This is fine and works well, but it becomes hard to maintain in the following scenario:
When you create a custom form input component, that basically wraps an input into it’s own re-usable component, we can no longer access the input’s value (and other props) reactively in e.g. a computed prop in the parent.
Take the following use-case:
<my-input ref="email"></my-input>
<my-input ref="password"></my-input>
<p>This is {{ isValid ? 'valid' : 'invalid' }}</p>
Previously we could create a computed prop like this:
isValid() {
return this.$refs.email.isValid && this.$refs.password.isValid
}
Since refs don’t work reactively anymore, we now need to use $emit
to inform the parent of changes.
However, these emits are handled by methods, so we need a separate handler per input to deal with the events.
Something like:
<my-input @valid="handleValidEmail"></my-input>
<my-input @valid="handleValidPassword"></my-input>
handleValidEmail(value) {
this.email = value
this.emailIsValid = true
},
handleValidPassword(value) {
this.password = value
this.passwordIsValid = false
}
You could refactor this a bit, but it’s not a nice way of dealing with this and I’m assuming using forms is quite a common occurence for a lot of devs.
Can we think about a better solution to something like this?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:116
- Comments:52 (13 by maintainers)
Top GitHub Comments
Although I don’t totally approve having reactive $refs as it can show a bad design choice in the model structure, I think it has its valid use cases so I created a small plugin to make
$refs
reactive: https://github.com/posva/vue-reactive-refs. It probably have caveats, so if you found any, please open an issue on the repo 🙂Just to add some context, this is what I could do previously:
But now I need to add additional state and a handler to deal with this:
Mainly the extra (not very useful) state and the handler are a bit of a pain, would be great if there could be some alternative to what used to be $refs that remain reactive. Not sure what the implications would be and why it was deprecated, I’m just trying to illustrate a use case when the old $refs were very useful.