本页面的代码:
点击按钮时不会触发方法,当把鼠标移到按钮上时就会调用方法?
<template>
<div class="p-4">
<div>测试页面是否正常显示</div>
<BasicTable
title="我是标题"
titleHelpMessage="我是温馨提醒"
:columns="columns"
:dataSource="data"
:canResize="canResize"
:loading="loading"
:striped="striped"
:bordered="border"
:pagination="{ pageSize: 20 }"
>
<!-- vben封装过后的操作按钮,toolbar是工具箱,在顶层 -->
<template #toolbar>
<a-button type="primary"> 操作按钮 </a-button>
</template>
<template #operation="{ record }">
<TableAction
stopButtonPropagation
:actions="[
{
label: '修改',
onClick: update(),
},
{
color: 'error',
label: '删除' ,
onClick: del(),
},
]"
/>
</template>
</BasicTable>
</div>
</template>
<script setup lang="ts">
import { defineComponent, ref, unref, nextTick,defineProps } from 'vue'
import { BasicTable, TableAction } from '/@/components/Table'
const props = defineProps();
const canResize = ref(true);
const loading = ref(false);
const striped = ref(true);
const border = ref(true);
const columns = ref([
{
title: 'ID',
dataIndex: 'id',
width: 80,
},
{
title: '名称',
dataIndex: 'name',
width: 200,
},
{
title: '年龄',
dataIndex: 'age',
width: 100,
},
{
title: '地址',
dataIndex: 'address',
},
{
title: '标题',
dataIndex: 'operation',
align: 'center',
width: 200,
slots: { customRender: 'operation' },
},
]);
const data =ref([
{
id: 1,
name: '张三',
age: 25,
address: '北京市',
},
{
id: 2,
name: '李四',
age: 30,
address: '上海市',
},
{
id: 3,
name: '王五',
age: 28,
address: '广州市',
},
])
function update(){
console.log('update方法执行了');
}
function del(e){
console.log(e)
console.log('delete方法执行了');
}
</script>
解决办法:
在上述代码中,我们需要将onClick的值更改为update和一个匿名箭头函数 ()=> del()。这样,在按钮被点击时,update函数和匿名箭头函数才会作为事件处理函数执行。
这样修改后,鼠标移动到按钮上时不会触发事件,只有在按钮被点击时才会执行相应的操作。
对应的代码:
:actions="[
{
label: '修改',
onClick: () => update(record),
},
{
color: 'error',
label: '删除',
onClick: () => del(111),
},
]"
原理:
问题在于这里的 onClick 属性:
onClick: update(),
在这里,你调用了 update() 函数,并将其返回值赋给了 onClick 属性。所以,当模板渲染时,update() 函数会立即执行,而不是等待按钮被点击时触发。
正确的做法是将 update() 函数本身传递给 onClick 属性,而不是调用它。可以通过去掉括号来实现。