vue3优雅的使用useDialog

在日常开发时,弹窗是一个经常使用的功能,而且重复性极高,你可能会遇到下面这些问题:

1、一个页面内多个弹窗, 要维护多套状态,看的眼花缭乱

2、弹窗内容比较简单,不想单独维护一套变量

关于这个问题, 我们首先想到的是一个即用即走的Dialog,不用去单独维护它的状态,我们使用Dialog({ xxx })这种形式去调用它,例如下面这种配置的方式:

js 复制代码
Dialog({
    title: 'xxx',
    render: () => xxx
})

其中render可以是一个html字符串,也可以是jsx(需要配置对jsx的支持),这样可以对内容区域实现充分的自定义。

通过配置项调用

各大主流的ui库基本都实现了这种调用方式:

之前没有注意到Element-plus的MessageBox可以使用jsx,大部分场景下,用它来代替Dialog还是很方便的。
示例代码:

js 复制代码
<script lang="jsx" setup>
import { reactive, ref } from 'vue';
import { ElMessageBox, ElForm, ElFormItem, ElInput } from 'element-plus'

const formRef = ref(null)
const form = reactive({ height: '', width: '' })
const rules = reactive({
  height: {
    required: true,
    trigger: 'blur'
  },
  width: {
    required: true,
    trigger: 'blur'
  }
})

function openMessageBox() {
  ElMessageBox({
    title: 'Message',
    showCancelButton: true,
    // message如果不是函数形式 绑定ref会失败
    message: () =>
      <ElForm
        ref={formRef}
        model={form}
        rules={rules}
      >
        <ElFormItem label="height" prop="height">
          <ElInput v-model={form.height}></ElInput>
        </ElFormItem>
        <ElFormItem label="width" prop="width">
          <ElInput v-model={form.width}></ElInput>
        </ElFormItem>
      </ElForm>
    ,
    beforeClose: (action, instance, done) => {
      console.log(action, instance)
      formRef.value && formRef.value.validate(status => {
        console.log('校验状态: ', status)
        if (status || action==='cancel') done()
      })
    }
  })
}
</script>

<template>
  <div class="container">
    <button @click="openMessageBox">
      打开messagebox
    </button>
  </div>
</template>

效果如下:

vueuse的createTemplatePromise

如果你不想使用jsx,而是想使用模板,vue的hooks工具库vueuse中提供了 createTemplatePromise 这个函数用来创建对话框、模态框、Toast 等,并且完全使用的是template的方式,因此自定义程度更高,并且没有任何额外成本(不需要jsx)。

下面是一个createTemplatePromise结合el-dialog的例子:

js 复制代码
<script lang="jsx" setup>
import { createTemplatePromise } from '@vueuse/core'
import { ElDialog, ElButton } from 'element-plus'

const TemplatePromise = createTemplatePromise()

async function open(idx) {
  console.log(idx, 'Before')
  const result = await TemplatePromise.start('Title', `Hello ${idx}`)
  console.log(idx, 'After', result)
}

function asyncFn() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('ok')
    }, 1000)
  })
}
</script>

<template>
  <div class="container">
    <button @click="open(1); open(2)">
      打开两个弹框
    </button>
  </div>
  <TemplatePromise v-slot="{ resolve, args, isResolving }">
    <el-dialog :modelValue="true" :title="args[0]">
      <div>Dialog {{ args[1] }}</div>
      <p>可以打开控制台查看logs</p>
      <div class="flex gap-2 justify-end">
        <el-button @click="resolve('cancel')">
          取消
        </el-button>
        <el-button type="primary" :disabled="isResolving" @click="resolve(asyncFn())">
          {{ isResolving ? 'loading...' : '确认' }}
        </el-button>
      </div>
    </el-dialog>
  </TemplatePromise>
</template>

效果如图:

Promise化Dialog的优点

这样有小伙伴可能会说, 这看起来和原来用dialog也没有很大区别啊, 也要写模版 + 函数方法. 那么让dialog变成这样有什么好处呢?

最大的好处是弹窗变得可编程了, 通过调用 Promise 的方式来控制UI, 不用再单独声明变量控制显隐, 也不用单独再去控制按钮的禁用、loading等状态, 例如以上的例子中, 我们可以轻松的处理button的loading状态(不用再额外声明变量), 我们让Dialog的UI和状态实现了內聚.

相关推荐
yuyuxun12 小时前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计
FungLeo6 小时前
成为全栈·Vue 管理后台篇·编辑器图片上传:从文件选择到文章附件关联
前端·vue.js·编辑器·markdown·文件上传·formdata·附件管理
nice_lcj5208 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
码云社区9 小时前
智慧物业系统选型指南:房屋档案、账单管理与报修协作
前端·javascript·vue.js·智慧物业
ruanno_top1 天前
表单重置后,验证码还显示已通过:Vue 受控组件的 3 种假同步
vue.js
聪明的笨猪猪1 天前
企业知识库AI架构选型:落地导向的架构决策与组件清单
经验分享·面试·架构·embedding·数据库架构
ruanno_top1 天前
给标签页加 roving tabindex,整组反而键盘进不去了
vue.js
仨孩子的爹1 天前
CSS打印样式:字体族与行高在纸上的对照实测
vue.js
OpenTiny社区1 天前
AI Agent场景组件库 TinyRobot v1.0 正式发布:一站式打造您的AI助手
vue.js·github