The examples provided for defineModel
in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to data exchange between parent and child components:
(app.vue):
<script setup lang="ts">
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const title = ref('v-model argument example with array')
const array = ref([1,2,3,4,5]);
</script>
<template>
<h1>{{ title }}</h1>
<MyComponent v-model:array = "array" />
<h2>Parent array: {{array}}</h2>
</template>
(myComponent.vue):
<script setup lang="ts">
const array = defineModel('array')
function ShortenArray() {
array.value = array.value.slice(1);
}
</script>
<template>
<button @click="ShortenArray">Shorten Array</button>
<p></p>
child array: {{ array }}
</template>
The code functions correctly, but a typescript error
Property 'slice' does not exist on type 'unknown'
is raised for array.slice()
, which remains unresolved.
Explore the Vue playground here.