ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Vue3中的defineModel

2026/9/23 15:56:16 拓冰建站 浏览量
Vue3中的defineModel

目录

一、vue3的defineModel介绍

二、defineModel使用

(1)在vite.config.js中开启

(2)子组件

(3)父组件


一、vue3的defineModel介绍

为什么要使用到defineModel呢?这里有这样一种场景:

子组件传递给父组件数据,并且实时更改。那么我们知道大概思路就是子组件使用defineEmits和defineProps来,但是这样很复杂,代码很多重复,实时更换让我们想到了v-model,所以我们就需要用到defineModel了。具体操作如下:

子组件的输入框数据变化,父组件也同样显示。

二、defineModel使用

(1)在vite.config.js中开启

 

(2)子组件

<template><div class="son"><h3>子组件</h3><input type="text" @input="e=>countvalue=e.target.value" :value="countvalue"> </div>  
</template><script setup>
import {defineModel} from 'vue'
const countvalue=defineModel()</script><style>
.son{border: 1px solid red;width: 200px;height: 200px;
}
</style>

(3)父组件

 

<template><div class="fa"><h3>父组件</h3><Son v-model="count"></Son>count={{ count }}</div>
</template><script setup>
import Son from './Son.vue';
import {ref} from 'vue'const count=ref(123445)
</script><style>
.fa{border: 1px solid black;width: 300px;height: 300px;
}
</style>