Vue3 + Naive UI 关于Popconfirm在table中的render写法

1,805 阅读15分钟

业务介绍:

在table中运用插槽写出和在DOM中一样的效果

技术栈和使用UI工具:

Vue3 + Naive UI

先说下不运用插槽,在template中的常规写法:

<n-popconfirm negative-text="取消" 
positive-text="确认" 
@positive-click="ignore" :show-icon="false">  
<template #trigger>    
<n-button color="#d4dbe7" text-color="#000"> 忽略 </n-button>  
</template>  确认忽略?</n-popconfirm>

大家可以看到哈,这种方法需要写入Popconfirm和Button标签,代码有些冗长

再说下如何运用插槽实现同样的效果:

首先:需要引入vue中的h函数,import { h } from 'vue' 按需引入NaiveUI对应的UI组件 import { NButton, NPopconfirm } from 'naive-ui'

其次在table中有个props:columns在里面写就逻辑就行,详细得可以上官网上看对应的API,代码如下:

render(row, index) {  
return [    
h( NPopconfirm,      
{ onPositiveClick: () => ignore(), negativeText: '取消', positiveText: '确认',},
{ trigger: () => h(NButton, 
{size: 'small',style: { marginRight: '12px' },},{ default: () => '忽略' },),
default: () => h('span', {}, { default: () => '确认忽略?' }),},)]

这里之所以在return写成数组的形式是因为我有三个按钮,后面会贴图表示;

那么现在就已经写好了Popconfirm最基本的显示方式,点击‘忽略’按钮显示气泡,下面是实现贴图:

再说下稍微复杂的业务,把上面的确认忽略替换成一个input要求用户填入误报的原因:

其实也不复杂就是替换一下input就行了,原理是一样的,下面看下代码:

h(NPopconfirm,  
{ onNegativeClick: () => errorReportCancel(), 
onPositiveClick: () => errorReportConfirm(),
negativeText: '取消',positiveText: '确认',showIcon: false},  
{trigger: () => h(NButton,
{type: 'warning',size: 'small',style: { marginRight: '12px' },},
{ default: () => '误报' },),
default: () => h(NInput, { placeholder: '确认为误报?请输入备注' }),},)

下面是实现贴图:

不知大家仔细看了没有,我这里写了三个按钮,所以我之前的render在return中返回的用的是数组的形式。

总结:

这就是Vue3在render中实现插槽的具体方法,不是很难,看一遍理解一下就能写了。

这里分享一个Vue3的组件库:www.naiveui.com/zh-CN/os-th…

这是我第一次在掘金做分享,说的不对的地方还请指教。以后还会经常分享,就当是把掘金当作做笔记的工具啦。

我是爱摄影,爱运动,爱coding的前端修白。