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 and computed.

  • We use defineProps to define a modelValue 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 the WritableComputedRef). The get function returns the current value of the modelValue prop, and the set 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.