vue3 ts setup 封装element-plus el-dialog,并使用v-model
封装 Element Plus 的 el-dialog 组件,并使其支持 v-model。
首先,确保你已经安装了 Element Plus,并在你的项目中正确引入了所需的样式和组件。然后,创建一个名为 CustomDialog.vue 的组件文件:
JavaScript 全选
<template>
<el-dialog v-model="visible">
<slot></slot>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue';
const props = defineProps({
modelValue: {
type: Boolean,
required: true
}
});
const emits = defineEmits(['update:modelValue']);
const visible = ref(props.modelValue);
watch(
() => props.modelValue,
(newValue) => {
if (visible.value != newValue) {
visible.value = newValue
}
}
)
watch(
() => visible.value,
(newValue) => {
if (props.modelValue != newValue) {
emit('update:modelValue', newValue)
}
}
)
</script>
在这个文件中,我们使用了 Vue 3 的 <script setup> 语法来创建组件的逻辑部分。我们使用 defineProps 来定义 props 对象,并使用 defineEmits 来定义 emits 对象,以便我们可以在 setup 中使用它们。
然后,我们使用 ref 创建了一个名为 visible 的响应式变量,并初始化为 props.modelValue。我们定义了一个 updateVisible 函数来更新 visible 变量,并触发 update:modelValue 事件。
最后,我们使用了 Element Plus 的 el-dialog 组件,将 visible 变量绑定到它的 v-model 上,并监听 update:visible 事件来更新 visible 变量。
现在,你可以在父组件中使用这个封装的对话框组件,并像这样使用 v-model:
JavaScript 全选
<template>
<div>
<button @click="dialogVisible = true">Open Dialog</button>
<custom-dialog v-model="dialogVisible">
<p>This is the content of the dialog</p>
</custom-dialog>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import CustomDialog from '@/components/CustomDialog.vue';
const dialogVisible = ref(false);
</script>
在这个示例中,我们将 dialogVisible 变量绑定到了 CustomDialog 组件的 v-model 上,这样就可以使用 dialogVisible 变量来控制对话框的显示和隐藏了。
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 张国生