vue3使用v-model在组件上实现双向绑定
1、官网地址
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父子组件的值双向绑定