分享一个项目是基于 vue + AntDesign 的。由于项目要求,需要在 Table 组件的行内点右键的时候弹出菜单。在线演示地址及最终效果图如下:
首先新建一个Table组件的实例:
<a-table
:columns="columns"
:rowKey="record => { return record.INDEX;}"
:dataSource="tableData"
/>
...
const columns = [
{
title: "序号",
dataIndex: "INDEX"
},
{
title: "主题大类",
dataIndex: "THEME"
},
{
title: "中文名称",
dataIndex: "CN_NAME"
},
{
title: "英文名称",
dataIndex: "EN_NAME"
}
];
...
data() {
return {
columns,
tableData: [
{ INDEX: 0, THEME: "基础数据", CN_NAME: "地区", EN_NAME: "Area" },
{ INDEX: 1, THEME: "个人信息", CN_NAME: "姓名", EN_NAME: "Name" }
]
};
}
新建一个Menu菜单组件的实例及其样式:
<a-menu :style="menuStyle" v-if="menuVisible">
<a-menu-item>{{menuData.THEME}}</a-menu-item>
<a-menu-item>{{menuData.CN_NAME}}</a-menu-item>
<a-menu-item>{{menuData.EN_NAME}}</a-menu-item>
</a-menu>
...
data() {
return {
...
menuData: {},
menuVisible: false,
menuStyle: {
position: "absolute",
top: "0",
left: "0",
border: "1px solid #eee"
}
};
}
注意这里给Menu加样式主要是为了实现点右键时Menu菜单出现在鼠标位置,所以我用了position: “absolute”来定义。
下面就是最重要的,通过Table组件的customRow参数来设置鼠标右键事件。首先添加Table组件的customRow参数:
<a-table
...
:customRow="customClick"
/>
然后在data里添加customClick的右键方法,以及在methods里添加body的click方法。添加body的click方法是为了在出现右键菜单后,点击左键时关闭菜单。
data() {
return {
...
customClick: record => ({
on: {
contextmenu: e => {
e.preventDefault();
this.menuData = record;
this.menuVisible = true;
this.menuStyle.top = e.clientY + "px";
this.menuStyle.left = e.clientX + "px";
document.body.addEventListener("click", this.bodyClick);
}
}
})
};
},
methods: {
bodyClick() {
this.menuVisible = false;
document.body.removeEventListener("click", this.bodyClick);
}
}
至此,Ant Design Vue中Table组件行内右键菜单就实现了。完整代码如下:
<template>
<div>
<a-table
:columns="columns"
:rowKey="record => { return record.INDEX;}"
:dataSource="tableData"
:customRow="customClick"
/>
<a-menu :style="menuStyle" v-if="menuVisible">
<a-menu-item>{{menuData.THEME}}</a-menu-item>
<a-menu-item>{{menuData.CN_NAME}}</a-menu-item>
<a-menu-item>{{menuData.EN_NAME}}</a-menu-item>
</a-menu>
</div>
</template>
<script>
const columns = [
{
title: "序号",
dataIndex: "INDEX"
},
{
title: "主题大类",
dataIndex: "THEME"
},
{
title: "中文名称",
dataIndex: "CN_NAME"
},
{
title: "英文名称",
dataIndex: "EN_NAME"
}
];
export default {
data() {
return {
columns,
tableData: [
{ INDEX: 0, THEME: "基础数据", CN_NAME: "地区", EN_NAME: "Area" },
{ INDEX: 1, THEME: "个人信息", CN_NAME: "姓名", EN_NAME: "Name" }
],
menuData: {},
menuVisible: false,
menuStyle: {
position: "absolute",
top: "0",
left: "0",
border: "1px solid #eee"
},
customClick: record => ({
on: {
contextmenu: e => {
e.preventDefault();
this.menuData = record;
this.menuVisible = true;
this.menuStyle.top = e.clientY + "px";
this.menuStyle.left = e.clientX + "px";
document.body.addEventListener("click", this.bodyClick);
}
}
})
};
},
methods: {
bodyClick() {
this.menuVisible = false;
document.body.removeEventListener("click", this.bodyClick);
}
}
};
</script>
作者:terry,如若转载,请注明出处:https://www.web176.com/news/frontend/28119.html