在使用vxe-grid@v2 版本中,v-slot:action=“{row,$rowIndex}” v-slot 插槽事件在切换菜单后,事件生效,但是没有双向绑定
两种写法
模板方式(
v-slot
)是声明式的,在编译时生成渲染函数,并且作用域是固定的(即父组件的实例)。配置方式(
slots
)是编程式的,在每次渲染时都会调用,生成新的VNode,并且可以访问到当前组件的状态(因为使用了箭头函数,绑定了当前组件的this
)。
模版写法
为 添加 :key=“row.id”,强制 Vue 在数据变更时重新渲染插槽。
<vxe-grid>
<vxe-column field="action" title="操作">
// 添加 key 强制更新 要不然事件触发,不能更新data中变量信息
<template v-slot:action="{ row }" :key="row.id">
<a @click="handleEdit(row, row.pkArea, modalKeys)">修改</a>
<a-divider type="vertical" />
<a-popconfirm
title="确定要删除吗?"
ok-text="确定"
cancel-text="取消"
placement="top"
@confirm="handleDelete(row.pkArea)"
>
<a>删除</a>
</a-popconfirm>
<a-divider type="vertical" />
<a @click="handlerRelevance(row.pkArea)">关联</a>
</template>
</vxe-column>
</vxe-grid>
插槽配置
columns: [
{
title: '操作',
field: 'action',
slots: {
default: ({ row }) => {
return [
h('a', {
on: {
click: () => this.handleEdit(row, row.pkArea, this.modalKeys)
}
}, '修改'),
h('a-divider', { props: { type: 'vertical' } }),
h('a-popconfirm', {
props: {
title: '确定要删除吗?',
okText: '确定',
cancelText: '取消',
placement: 'top'
},
on: {
confirm: () => this.handleDelete(row.pkArea)
}
}, [ h('a', {}, '删除') ]),
h('a-divider', { props: { type: 'vertical' } }),
h('a', {
on: {
click: () => this.handlerRelevance(row.pkArea)
}
}, '关联')
]
}
}
}
]
扩展内容
混合模式(动态列 + 渲染函数) 结合 v-slot 的易读性和渲染函数的可靠性:
<template>
<vxe-column field="action" title="操作">
<template v-slot:action="{ row }">
// 调用渲染函数生成内容
<render-action :row="row" />
</template>
</vxe-column>
</template>
export default {
methods: {
actionSlots(h) {
return ({ row }) => [
// 渲染函数内容和插槽配置一样
];
}
}
}
响应式更新机制差异:
v-slot 是 Vue 的模板语法,依赖 Vue 的响应式系统更新。但在某些动态场景(如表格数据切换)中,可能因作用域或上下文未正确更新导致失效。
slots 配置是编程式渲染函数,每次渲染都会重新创建内容,能直接绑定当前组件实例的 this,确保上下文正确。