#development #frontend #javascript #typescript #vuejs
Previously, for a component to support two-way binding with v-model
, it needs to (1) declare a prop and (2) emit a
corresponding update:propName
event when it intends to update the prop:
1<!-- BEFORE -->
2<script setup>
3const props = defineProps(['modelValue'])
4const emit = defineEmits(['update:modelValue'])
5console.log(props.modelValue)
6
7function onInput(e) {
8 emit('update:modelValue', e.target.value)
9}
10</script>
11
12<template>
13 <input :value="modelValue" @input="onInput" />
14</template>
3.3 simplifies the usage with the new defineModel
macro. The macro automatically registers a prop, and returns a ref
that can be directly mutated:
1<!-- AFTER -->
2<script setup>
3const modelValue = defineModel()
4console.log(modelValue.value)
5</script>
6
7<template>
8 <input v-model="modelValue" />
9</template>
This feature is experimental and requires explicit opt-in.
When you use Vite, you can enable it like this:
1// vite.config.js
2export default {
3 plugins: [
4 vue({
5 script: {
6 defineModel: true
7 }
8 })
9 ]
10}
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.