Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active April 16, 2024 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/714c0c221728ddde0c6104eb1434c4d0 to your computer and use it in GitHub Desktop.
Save Kcko/714c0c221728ddde0c6104eb1434c4d0 to your computer and use it in GitHub Desktop.
<!-- 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment