vue3 element plus 自定义组件封装,多层双向绑定v-model

日常,我们可能对element plus的组件进行进一步封装,而且可能是多层,那么要想实现双向绑定:

  1. 显式

:绑定属性,@绑定事件,事件中修改属性

  1. 隐式

v-model

第一种无需多说,第二种简单示例,以Dialog组件示例

  • 直接使用
    Dialog.vue
<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>
  • 一层封装
    Dialog.vue
<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>
  • 两层封装
    Dialog.vue
<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变量,然后通过事件进行变化值传递)

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值