On gists
v-model, defineModel, composition api
•
Popular ⭐
Vue.js
example.vue
Raw
#
<!-- Parent -->
<template>
<CommonInput v-model="inputValue" />
</template>
<script setup lang="ts">
import { ref } from "vue";
const inputValue = ref();
</script>
<!-- Child -->
<template>
<input
:value="props.modelValue"
@input="emit('update:modelValue', $event.target.value)"
/>
</template>
<script setup lang="ts">
const props = defineProps(["modelValue"]);
const emit = defineEmits(["update:modelValue"]);
</script>
<!-- **************** With defineModel **************** -->
<!-- https://javascript.plainenglish.io/understanding-vue-3s-definemodel-for-two-way-binding-streamline-your-code-with-this-guide-ac970f365e4a -->
<!-- Parent -->
<template>
<CommonInput v-model="inputValue" />
</template>
<script setup lang="ts">
import { ref } from "vue";
const inputValue = ref();
</script>
<!-- Child -->
<template>
<input v-model="model" />
</template>
<script setup lang="ts">
// declares "modelValue" prop, consumed by parent via v-model
const model = defineModel();
// emits "update:modelValue" when mutated
model.value = "hello";
</script>
<!-- **************** Without defineModel **************** -->
<!-- Child -->
<template>
<input v-model="props.modelValue" />
</template>
<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
const props = defineProps(["modelValue"]);
const emit = defineEmits(["update:modelValue"]);
</script>
<!-- OR with computed, probably better-->
<!-- Child -->
<template>
<input v-model="inputValue" />
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
const inputValue = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
});
</script>