关于 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>
代码对应的视图样式图片:
标签:const,score,示例,defineModel,Vue3.4,msg,ref From: https://www.cnblogs.com/fanqshun/p/18216210