vue3使用v-model父子组件的值双向绑定

文章详细介绍了在Vue3中如何使用v-model和defineEmits在子组件和父组件之间实现数据的双向绑定,通过子组件触发事件更新父组件的状态,并提供了一个具体的ElementPlus库中的对话框组件示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue3使用v-model在组件上实现双向绑定

1、官网地址

v-model链接

2、如何使用

  • 子组件:通过defineEmits([‘update:dialogVisible’]) 设置监听的数据,update后面跟的是自定义名称
  • 子组件:通过事件将执行emits(‘update:dialogVisible’,false),第二个参数是你要修改的参数,我这边是直接更改成false,目的是为了让弹窗隐藏
  • 父组件:在父组件中通过在子组件绑定 v-model:dialogVisible=“isShow”,从而实现在组件上实现双向绑定
// 子组件
<template>
  <el-dialog
    :model-value="dialogVisible"
    title="Tips"
    width="30%"
    :before-close="handleClose"
  >
    <span>This is a message</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfrim">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
const emits = defineEmits(['update:dialogVisible'])
let props = defineProps({
  dialogVisible:{
    type:Boolean,
    default:false
  }
})
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      emits('update:dialogVisible',false)
      done()
    })
    .catch(() => {
      // catch error
    })
}
const handleConfrim = () => {
  emits('update:dialogVisible',false)


}
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>

// 父组件
<script setup lang="ts">
import { ref } from 'vue';
import HelloWorld from './components/HelloWorld.vue'
let isShow = ref<boolean>(false)
const handleBtnClick = () => {
  isShow.value = true
}
</script>

<template>
  <el-button text @click="handleBtnClick">
    click to open the Dialog
  </el-button>
  <div class="wrapper">
    // 通过v-model对子组件进行双向绑定
    <HelloWorld v-model:dialogVisible="isShow"  />
  </div>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>

3、对比与vue2的区别

在vue2中我们可以使用sync和v-model两中方式来进行组件之间的绑定,vue3好像优化到只使用v-model进行双向绑定
vue2使用sync修饰符父子组件的值双向绑定
vue2使用v-model父子组件的值双向绑定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月落星河°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值