vue3使用defineModel实现父子组件双向绑定
更新时间:2024年01月11日 10:00:02 作者:一天只码五十行
这篇文章主要个给大家介绍了在vue3中使用defineModel进行父子组件中的双向绑定,文中通过代码示例给大家介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
在vue3.4版本中,defineModel进入稳定版。我们可以使用defineModel来优化父子组件中的双向绑定。在3.3之前的版本中,双向绑定需要在使用props和emits传值,现在我们只需要一行代码就可以解决这个问题:const 变量名=defineModel()
在子组件Helloworld.vue中:
<template>
<div class="page">
<input
type="text"
:value="fonts"
@input="(e:any) => (fonts= e.target.value)"
size="large"
class="inputBox"
/>
</div>
</template>
<script lang="ts" setup>
import { defineModel } from "vue";
const fonts = defineModel();
</script>
<style scoped lang="less">
.page {
width: 600px;
height: 150px;
}
</style>在父组件中:
<template>
<div class="home">
<div class="mian">
<div class="text">{{ fonts }}</div>
<HelloWorld v-model="fonts" />
</div>
</div>
</template>
<script lang="ts" setup>
import HelloWorld from "@/components/HelloWorld.vue";
import { ref } from "vue";
const fonts = ref<string>("aaa");
</script>
<style>
.home {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
</style>再看看效果

以上就是vue3使用defineModel实现父子组件双向绑定的详细内容,更多关于vue3 defineModel父子组件绑定的资料请关注脚本之家其它相关文章!
相关文章
浅谈一下Vue生命周期中mounted和created的区别
每一个vue实例从创建到销毁的过程,就是这个vue实例的生命周期,在这个过程中,他经历了从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,那么这些过程中,具体vue做了些啥,我们今天来了解一下2023-05-05


最新评论