vue3.0 + element Plus实现页面中引入弹窗组件及defineExpose用法

1. 在需要弹窗显示的页面引入你所写的弹窗组件(index.html) 

<template>
<!--按钮用来触发弹窗-->
 <el-button
     type="primary"
     plain
     @click="onProcess()"
     :icon="View"
  >更新进度</el-button>
  <teleport to="body">
    <!-- 弹窗组件,ref一定要写 -->
    <sync-process-dialog
      :data="syncProcess"
      ref="processDailogRef"  
    ></sync-process-dialog>
  </teleport>
</template>

2. 在js文件中设置ref的值及通过按钮触发打开弹窗

<script lang="ts" setup>
import { ref } from "vue";
import { View } from "@element-plus/icons";

const processDailogRef = ref();

//查看一键更新进度
//onChangeVisable()为子组件中通过defineExpose暴露出来的
const onProcess = () => {
  processDailogRef.value.onChangeVisable();
};

</script>

3. 在子组件中接受父组件传值,并显示弹窗(父组件通过模板 ref 的方式获取到当前组件的实例,SyncProcessDialog.vue)

<!--当前文件为子组件即父组件引入的,SyncProcessDialog.vue-->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    :close-on-click-modal="false"
    title="更新进度"
    width="850px"
  >
   <div>弹窗内容</div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref } from "vue";

//这里是接受父组件传递的值
const props = withDefaults(
  defineProps<{
    data: object;
  }>(),
  {}
);

const dialogFormVisible = ref(false);
const onChangeVisable = () => {
  dialogFormVisible.value = true;
};

defineExpose({ onChangeVisable });
</script>

效果展示:

Vue3 ,打开弹 dialog 可以使用组件实现。以下是一个简单的实现示例: 父组件代码: ```vue <template> <div> <button @click="openDialog">打开弹</button> <dialog :visible="dialogVisible" @close="closeDialog"> <h3>这是一个弹</h3> <p>这里可以放置弹的内容</p> </dialog> </div> </template> <script> import Dialog from './Dialog.vue'; export default { components: { Dialog }, data() { return { dialogVisible: false } }, methods: { openDialog() { this.dialogVisible = true; }, closeDialog() { this.dialogVisible = false; } } } </script> ``` 子组件 Dialog 代码: ```vue <template> <div class="dialog" v-if="visible"> <div class="dialog-content"> <slot></slot> <button @click="$emit('close')">关闭弹</button> </div> </div> </template> <script> export default { props: { visible: { type: Boolean, default: false } } } </script> <style> .dialog { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .dialog-content { background-color: #fff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } </style> ``` 当点击打开弹按钮时,会将 dialogVisible 属性设置为 true,使子组件 Dialog 显示出来。Dialog 组件会根据 visible 属性来判断是否显示,当 visible 属性为 true 时显示,为 false 时隐藏。 当点击关闭弹按钮时,会触发子组件 Dialog 的 close 事件,并将 dialogVisible 属性设置为 false,使 Dialog 组件隐藏起来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值