With the upcoming Vue.js version 3.3, the community once again doesn’t disappoint. Vue.js 3.3 includes many useful features that improve productivity and developer velocity.
One exciting new feature is defineModel, which allows us to implement much smoother two-way binding. Let’s demonstrate its usage in the following blog post.
What is Two-Way Binding?
Two-way binding is a feature in Vue that allows changes in the data to update the view automatically and vice versa. This means that when the user updates the view, the underlying data is also updated, and when the data is updated programmatically, the view is automatically updated to reflect the new data. It is achieved using the v-model
directive, which binds a form input element to a piece of data.
<template>
<input v-model="message" />
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello from Bitovi!')
</script>
Two-way binding is useful because it eliminates the need for manual event handling to keep the view and data in sync, which can be tedious and error-prone. Using v-model
is the equivalent of the following:
<template>
<input :value="message" @input="message = $event.target.value" />
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello from Bitovi!')
</script>
Now that you know why two-way binding in Vue is so exciting, let's explore a use case where custom two-way binding makes sense.
Custom Two-Way Binding
One example of two-way binding is a custom search component that allows the user to type some value into the search, which will display multiple options until he chooses one. This behavior is demonstrated in the following code:
// MySearch.vue
<template>
<div>
<!-- search text input -->
<input v-model="searchRef" type="text" placeholder="Search.." />
<!-- display selected value -->
<div v-if="props.modelValue">
Selected: {{ props.modelValue.title }}
</div>
<!-- results -->
<div v-if="searchRef.length > 3">
<button
v-for="data in store.getLoadedElements"
:key="data.id"
@click="onClick(data)"
>
{{ data.title }}
</button>
</div>
</div>
</template>
<script setup lang="ts">
// imports
const store = useStore();
const props = defineProps({
modelValue: {
type: Object as PropType<Element | null>,
required: false,
default: null
}
});
const emit = defineEmits<{
(e: "update:modelValue", value: Element): void;
}>();
// reference to search input
const searchRef = ref<string>("");
// fetch data from API
watchEffect(() => {
store.fetchElements(searchRef.value);
});
const onClick = (data: Element) => {
emit("update:modelValue", data);
};
</script>
In the above example, to make the custom two-way binding work, you use defineProps
to create a modelValue
input property for the component, and you use the defineEmits
with update:modelValue
to notify the parent about the change.
The usage of the above child component is achieved by the following syntax in another component.
<MySearch v-model="someRef" />
<!-- same as -->
<MySearch
:modelValue="someRef"
@update:modelValue="someRef = $event"
/>
Tip: You can define multiple properties for the MySearch
component into the defineProps
and defineEmits
.
The name modelValue
is the name for the default value, however creating multiple properties, you can access them in the parent component by <MySearch v-model:first="first" v-model:second="second"/>
.
Using defineModel
With Vue.js version 3.3 comes a new defineModel macro. You no longer need to write out all the above-mentioned steps to implement custom two-way binding.
This new feature is available from version-3.3.0-alpha.9. However, It is still considered an experimental feature. If you wish to use it or have difficulty upgrading to version 3.3, you can still use defineModels,
the alternative from the Vue Macros library. Overall, they work the same way.
After completing the installation guidelines, you can use defineModels with the following syntax:
// MySearch.vue
<template>
<div>
<!-- search text input -->
<input v-model="searchRef" type="text" placeholder="Search.." />
<!-- display selected value -->
<div v-if="modelValue">Selected: {{ modelValue.title }}</div>
<!-- results -->
<div v-if="searchRef.length > 3">
<button
v-for="data in store.getLoadedElements"
:key="data.title"
@click="modelValue = data"
>
{{ data.title }}
</button>
</div>
</div>
</template>
<script setup lang="ts">
// imports
const store = useStore();
const { modelValue } = defineModels<{ modelValue: Element }>();
// reference to search input
const searchRef = ref<string>("");
// fetch data from API
watchEffect(() => {
store.fetchElements(searchRef.value);
});
</script>
The macro defineModels
replaces the previously used defineProps
and defineEmits
into one functionality.
Each time the user passes some value to this component by <MySearch :modelValue="someRef" />
the MySearch
component will be updated and also on the other hand, in line 16, when the user selects an element, by modelValue = data
, the listener on the parent component will be triggered.
Summary
It’s great to see that the Vue.js team recognizes valuable contributions from developers to the Vue ecosystem, and over time, they ship their implementation. With the upcoming version 3.3, Vue.js brings us many more useful tools that will speed up our development.
For more information about using Vue, check out our training program or book your free Vue.js consulting call to discuss your project with an expert.
What do you think?
Drop into our Community Discord to share your thoughts about Vue.js. Our community of friendly experts would love to chat!