T
TanStack16mo ago
xenial-black

Can I bind a field to a Vue reactive object?

I have a custom input component that needs to be bound to a ref. How do I get this to work with Tanstack Form? What I've done is use a combination of watchEffect and setFieldValue, but this feels very clunky:
<script setup>
const form = useForm(...);

const username = ref('');
watchEffect(() => {
form.setFieldValue('username', username.value);
});
</script>

<template>
<form>
<CustomInput v-model="username"></CustomInput>
</form>
</template>
<script setup>
const form = useForm(...);

const username = ref('');
watchEffect(() => {
form.setFieldValue('username', username.value);
});
</script>

<template>
<form>
<CustomInput v-model="username"></CustomInput>
</form>
</template>
8 Replies
fair-rose
fair-rose16mo ago
This is really discouraged, as it creates problems with bi-directionality. We highly encourage binding via the :value property and @input event. YMMV outside of this
xenial-black
xenial-blackOP16mo ago
@crutchcorn I understand this creates some issues... But I just don't see a way around it if the custom component I'm working with does not support binding with :value?
fair-rose
fair-rose16mo ago
v-model is shorthand. You can just use the expanded syntax for value and event binding manually: https://vuejs.org/guide/components/v-model.html#under-the-hood
Vue.js
Vue.js - The Progressive JavaScript Framework
xenial-black
xenial-blackOP16mo ago
@crutchcorn Ah, I see. I tried that before, but I was having an issue with the input emptying. So I thought that was the wrong approach. But now I see that it's because the custom component in question emits a different event than a regular input's blur event, which was causing the field to be set to undefined when used with @onBlur="(e) => field.handleChange(e.target.value)" Thanks!
fair-rose
fair-rose16mo ago
No prob! Hey BTW, any chance you wanna make a PR to our Vue docs to add this mention? It'd almost for sure be helpful for others ✨
xenial-black
xenial-blackOP16mo ago
@crutchcorn sure @crutchcorn I was actually thinking of setting up a repo with the react examples for tanstack table translated into vue among other things but I really need to get up to speed on TypeScript before I do that
fair-rose
fair-rose16mo ago
That'd be awesome! CC @KevinVandy Anything I can do to help answer any questions or whatnot?
xenial-black
xenial-black16mo ago
Yeah, just make PRs to table if you want to add more Vue examples

Did you find this page helpful?