日常,我们可能对element plus的组件进行进一步封装,而且可能是多层,那么要想实现双向绑定:
:绑定属性,@绑定事件,事件中修改属性
v-model
第一种无需多说,第二种简单示例,以Dialog组件示例
<template>
<el-button @click="handleClick">切换</el-button>
<el-dialog v-model="visible"></el-dialog>
</template>
<script setup lang="ts">
const visible=ref(false)
const handleClick=()=>{
visible.value=!visible.value;
}
</script>
<style scoped></style>
<template>
<el-dialog v-model="visible"></el-dialog>
</template>
<script setup lang="ts">
const props = defineProps({
modelValue: {
type: Boolean,
default: false,
},
});
const visible = computed({
get: () => props.modelValue,
set: val => {
emit("update:modelValue", val);
},
});
const emit = defineEmits(["update:modelValue"]);
</script>
<style scoped></style>
BaseDialog.vue
<template>
<el-button @click="handleClick">切换</el-button>
<Dialog v-model="visible"></Dialog>
</template>
<script setup lang="ts">
import Dialog from './Dialog.vue'
const visible=ref(false)
const handleClick=()=>{
visible.value=!visible.value;
}
</script>
<style scoped></style>
<template>
<el-dialog v-model="visible"></el-dialog>
</template>
<script setup lang="ts">
const props = defineProps({
modelValue: {
type: Boolean,
default: false,
},
});
const visible = computed({
get: () => props.modelValue,
set: val => {
emit("update:modelValue", val);
},
});
const emit = defineEmits(["update:modelValue"]);
</script>
<style scoped></style>
BaseDialog.vue
<template>
<Dialog v-model="visible"></Dialog>
</template>
<script setup lang="ts">
import Dialog from './Dialog.vue'
const props = defineProps({
modelValue: {
type: Boolean,
default: false,
},
});
const visible = computed({
get: () => props.modelValue,
set: val => {
emit("update:modelValue", val);
},
});
const emit = defineEmits(["update:modelValue"]);
</script>
<style scoped></style>
CustomDialog.vue
<template>
<el-button @click="handleClick">切换</el-button>
<BaseDialog v-model="visible"></BaseDialog>
</template>
<script setup lang="ts">
import BaseDialog from './BaseDialog.vue'
const visible=ref(false)
const handleClick=()=>{
visible.value=!visible.value;
}
</script>
<style scoped></style>
总结:多层双向绑定时,除了最上层v-model绑定ref变量,其他层都绑定计算属性,并且计算属性实现getter和setter(当然也可以不用计算属性,依然绑定ref变量,然后通过事件进行变化值传递)