We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Vue 3 introduced the Composition API, a flexible way to define and manage component logic. One common use case in Vue
components is to enable two-way binding using the v-model
directive. In this blog post, we'll explore how to use the
WritableComputedRef
to implement v-model
support in Vue 3 when using the Composition API.
Understanding v-model
Before diving into the implementation, let's briefly recap what v-model
is and why it's useful. In Vue, v-model
is a
convenient way to create a two-way binding between a parent component's data and a child component's prop. It allows you
to easily pass data down to a child component and update it in response to user input, all with a clean and declarative
syntax.
Using WritableComputedRef
To implement v-model
support using the Composition API, we can utilize the WritableComputedRef
. This function
combines the reactivity of a computed property with the ability to set its value, making it perfect for handling
v-model
bindings.
Here's a code sample demonstrating how to use WritableComputedRef
to implement v-model
support in a Vue 3 component:
<script setup>
import { defineProps, defineEmits, computed } from 'vue';
const props = defineProps({
modelValue: {
type: Object,
required: true,
},
});
const emit = defineEmits(['update:modelValue']);
const computedModel = computed({
get() {
return props.modelValue;
},
set(value) {
emit('update:modelValue', value);
},
});
</script>
In the code above:
-
We import the necessary functions from Vue 3, including
defineProps
,defineEmits
andcomputed
. -
We use
defineProps
to define amodelValue
prop, which will be used for two-way binding. -
We define the
emit
function to emit an event named'update:modelValue'
when we want to update the prop value. -
We create a computed value called
computedModel
(this is theWritableComputedRef
). Theget
function returns the current value of themodelValue
prop, and theset
function emits an event to update the prop value when necessary.
Now, you can use v-model
to bind the prop in your component's template:
<template>
<input v-model="myProperty" />
</template>
With this setup, changes made to the <input>
element will automatically update the myProperty
prop, and changes to
the myProperty
prop in the parent component will be reflected in the child component.
Conclusion
Using the WritableComputedRef
in Vue 3's Composition API makes implementing v-model
support clean and efficient. It
allows you to create two-way data bindings with ease, simplifying the communication between parent and child components.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.