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变量,然后通过事件进行变化值传递)

你可能感兴趣的:(vue,element,plus,vue.js,前端,elementui)