關於 defineModel ,Vue官方給出了較為詳細的解釋,具體請看 文件說明
下面是整理出的一個簡易示例:
子元素程式碼:
// Comp.vue
<script setup>
const msg = defineModel('msg', { type: String, default: '' });
const score = defineModel('score', { type: Number, default: 0 });
/**
* 更新score(同步更新父元素中的資料)
*/
const onClick = () => {
score.value += 1;
};
</script>
<template>
<div style="margin: 10px;padding: 8px;background-color: azure;">
<span>子元件</span>
<div>
<input v-model="msg" />
</div>
<span>dubble score: {{score * 2}}</span>
<br />
<button @click="onClick">score + 1</button>
</div>
</template>
父元素程式碼:
<script setup>
import Comp from './Comp.vue';
import { ref } from 'vue';
const msg = ref('Hello World!');
const score = ref(1);
</script>
<template>
<div style="border: 1px solid goldenrod">
<span>父元件</span>
<h1>{{ msg }}</h1>
<h2>origin-score: {{score}}</h2>
</div>
<Comp
v-model:msg="msg"
v-model:score="score"
/>
</template>
程式碼對應的檢視樣式圖片: