使用vue3+elementsplus封装一个提示确认框的组件,要求将请求地址和确认框展示信息作为参数暴露出去
时间: 2024-05-18 08:18:56 浏览: 239
好的,下面是使用 Vue3 和 ElementPlus 封装一个提示确认框的组件,同时将请求地址和确认框展示信息作为参数暴露出去。
```vue
<template>
<el-dialog
title="确认提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose"
>
<p>{{ message }}</p>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleConfirm">确定</el-button>
</span>
</el-dialog>
</template>
<script>
import { defineComponent, ref } from 'vue';
import { ElDialog, ElButton } from 'element-plus';
export default defineComponent({
name: 'ConfirmDialog',
components: {
ElDialog,
ElButton,
},
props: {
apiUrl: {
type: String,
default: '',
},
message: {
type: String,
default: '',
},
},
setup(props) {
const dialogVisible = ref(false);
// 确认操作
const handleConfirm = () => {
// 发起请求
// ...
// 关闭确认框
dialogVisible.value = false;
};
// 取消操作
const handleClose = (done) => {
dialogVisible.value = false;
done();
};
return {
dialogVisible,
handleConfirm,
handleClose,
};
},
});
</script>
```
在上面的代码中,我们使用 `defineComponent` 函数来定义一个 Vue3 组件,并且引入了 ElementPlus 的 `ElDialog` 和 `ElButton` 组件。我们通过 `props` 属性将 `apiUrl` 和 `message` 两个参数暴露出去,分别用于存放请求地址和确认框展示信息。
在 `setup` 函数中,我们使用 `ref` 函数来创建一个名为 `dialogVisible` 的响应式变量,用于控制确认框的显示和隐藏。我们同时定义了 `handleConfirm` 和 `handleClose` 两个函数,用于处理确认和取消操作。
在模板中,我们使用 ElementPlus 的 `el-dialog` 组件来展示确认框,通过 `visible.sync` 属性将 `dialogVisible` 和确认框的显示状态绑定起来。在确认框的内容部分,我们通过插值绑定将 `message` 展示出来,同时设置了确认和取消两个按钮,分别绑定了 `handleConfirm` 和 `handleClose` 两个函数。
在 `handleConfirm` 函数中,我们可以根据 `apiUrl` 发起请求,然后在请求成功后关闭确认框。在 `handleClose` 函数中,我们只需要将 `dialogVisible` 设置为 false,然后调用 `done` 函数即可关闭确认框。
最后,我们将组件导出,即可在其他地方使用。例如:
```vue
<template>
<div>
<el-button type="primary" @click="dialogVisible = true">打开确认框</el-button>
<confirm-dialog :apiUrl="apiUrl" :message="message" />
</div>
</template>
<script>
import { defineComponent, ref } from 'vue';
import ConfirmDialog from './ConfirmDialog.vue';
export default defineComponent({
name: 'TestComponent',
components: {
ConfirmDialog,
},
setup() {
const dialogVisible = ref(false);
const apiUrl = 'http://example.com/api';
const message = '确认要进行此操作吗?';
return {
dialogVisible,
apiUrl,
message,
};
},
});
</script>
```
在上面的代码中,我们引入了刚才封装的确认框组件,然后在模板中使用一个按钮来触发显示确认框。同时,我们将 `apiUrl` 和 `message` 两个参数传递给确认框组件。
阅读全文