実験的な新機能らしい
まず、vueのバージョンを最新のVue3.3にしておきます。
実験的な機能のためそのままでは使えないので、
使えるようにviteとかの設定を変えないといけない。
Nuxtの場合はこんな感じ
nuxt.config.ts
export default defineNuxtConfig({
vite: {
vue: {
script: {
defineModel: true,
propsDestructure: true
}
}
}
...
親のコンポーネントは普通にv-modelする。
parent.vue
<script lang="ts" setup>
const count = ref<number>(0);
</script>
<template>
<p>{{ count }}</p>
<Child v-model="count" />
</template>
子供でdefineModelする。
child.vue
<script setup lang="ts">
const count = defineModel<number>();
</script>
<template>
<p>{{ count }}</p>
<button @click="count!++">click</button>
</template>
v-modelに別名つけたい時はこうするのかな
//parent
v-model:sampleName="count"
//child
const count = defineModel<number>('sampleName');
あとオプションとかも色々あるみたいだけどまだよく分からない。