在一次业务开发时代码时,碰到了一种既想要Modal.confirm
样式,又想要定制其content
内容的情况。
大部分情况下,使用Modal.method()
这种方式时,可能content
内容固定都是字符串,那如果想要做更高级的交互怎么办?查阅 Ant Design Vue官方文档,发现content可以不仅仅是字符串:
可以看到content是可以接收VNode或h函数的,下面分别讲解,这两种参数的用法
VNode形式
1、创建一个组件
<template> <div class="d-flex"> <span>{{ props.text }}</span> <img src="https://pic.616pic.com/ys_img/00/31/95/oGv09XRm2b.jpg" class="jc-arrow" @click="onClickSetting" /> </div> </template> <script setup lang="ts"> export interface Props { text: string; } const props = withDefaults(defineProps<Props>(), { text: undefined, }); const onClickSetting = () => { console.log('click setting'); }; </script> <style lang="less" scoped> .jc-arrow { width: 20px; height: 20px; } </style>
复制
2、在需要使用的地方引入该组件,并且从Vue中引入createVNode函数
// 引入组件 import JumpConfirm from './JumpConfirm.vue'; // 引入函数 import { createVNode } from 'vue';
复制
- 调用
state.modal = Modal.confirm({ title: '模态框title', content: createVNode(JumpConfirm, { text: '重置', }), centered: true, okText: countdownText.value, onOk: async () => { clearCountdown(); }, onCancel: () => { clearCountdown(); }, });
复制
createVNode第一个参数传的是组件,第二个参数传的是组件需要的props。
比如我上面的组件定义了接收Props在组件中使用,所以我这里第二个参数传的就是我前面定义的Props需要的参数
4、效果
h函数形式
h函数用法请参考官方文档:https://vue3js.cn/global/h.html
const builtIns = ['模板1', '模板2', '模板3', '模板4']; Modal.confirm({ title: '以下模板不可删除', centered: true, content: h( 'div', { style: { 'max-height': '200px', 'overflow-y': 'auto', }, }, [h('p', {class: 'c-t05 font-xs'}, '内置模板'), h('p', {class: 'c-t01 font-13'}, builtIns.join(','))] ),
复制