Cannot correctly override onClick in v-bind #13869
Replies: 2 comments
-
|
https://vuejs.org/api/render-function.html#mergeprops |
Beta Was this translation helpful? Give feedback.
-
|
Hello! This behavior is expected due to how Vue's The Issue:
Solution 1: Conditional v-bind <script setup>
const { locale, t } = useI18n();
const items = [
{
title: 'change language',
props: {
onClick: () => (locale.value = locale.value === 'zh-CN' ? 'en-US' : 'zh-CN'),
},
disabled: true,
},
]
const onClick = (e, item) => {
if (item.disabled) return;
item.props?.onClick?.(e);
};
</script>
<template>
<div
v-for="(item, i) in items"
:key="i"
v-bind="item.disabled ? {} : item.props"
@click="(e) => onClick(e, item)"
>
</div>
</template>Solution 2: Manual Event Handling <script setup>
const { locale, t } = useI18n();
const items = [
{
title: 'change language',
action: () => (locale.value = locale.value === 'zh-CN' ? 'en-US' : 'zh-CN'),
disabled: true,
},
]
const onClick = (e, item) => {
if (item.disabled) return;
item.action?.();
};
</script>
<template>
<div
v-for="(item, i) in items"
:key="i"
v-bind="item.props"
@click="(e) => onClick(e, item)"
>
</div>
</template>Solution 3: Separate Props from Events <script setup>
const { locale, t } = useI18n();
const items = [
{
title: 'change language',
onItemClick: () => (locale.value = locale.value === 'zh-CN' ? 'en-US' : 'zh-CN'),
otherProps: {
class: 'some-class',
style: { color: 'red' }
},
disabled: true,
},
]
const onClick = (e, item) => {
if (item.disabled) return;
item.onItemClick?.(e);
};
</script>
<template>
<div
v-for="(item, i) in items"
:key="i"
v-bind="item.otherProps"
@click="(e) => onClick(e, item)"
>
</div>
</template>Solution 4: Event Handler Wrapper <script setup>
const { locale, t } = useI18n();
const items = [
{
title: 'change language',
props: {
onClick: () => (locale.value = locale.value === 'zh-CN' ? 'en-US' : 'zh-CN'),
},
disabled: true,
},
]
const handleClick = (e, item) => {
if (!item.disabled) {
item.props?.onClick?.(e);
}
};
</script>
<template>
<div
v-for="(item, i) in items"
:key="i"
v-bind="{ ...item.props, onClick: undefined }"
@click="(e) => handleClick(e, item)"
>
</div>
</template>Recommended Approach: The key insight is that Vue's |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Vue version
3.5.13
Link to minimal reproduction
https://cn.vuejs.org/
Steps to reproduce
What is expected?
The item's onclick should be blocked from being triggered because it's disabled.
What is actually happening?
item.onclick is still triggered.
System Info
Any additional comments?
No response
Beta Was this translation helpful? Give feedback.
All reactions