【发布时间】:2020-04-06 12:37:49
【问题描述】:
请看这个最小的例子:
我有一个最小的自定义按钮,叫做MyButton,就像这样
<template>
<button @click="click">
<slot />
</button>
</template>
<script>
export default {
methods: {
click(event) {
this.$emit('click', event)
}
}
};
</script>
现在,我像这样使用<MyButton />
<template>
<div>
<MyButton @click="click(event)">Click</MyButton>
</div>
</template>
<script>
import MyButton from "./components/MyButton";
export default {
components: {
MyButton
},
methods: {
click(event) {
alert(
JSON.stringify(event.currentTarget.getBoundingClientRect(), null, 2)
);
}
}
};
</script>
此代码因以下控制台错误而中断
[Vue warn]: Property or method "event" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'currentTarget' of undefined"
TypeError: Cannot read property 'currentTarget' of undefined
但是,如果我将@click="click(event)" 更改为@click="click($event)",现在我的代码可以正常工作!
为什么会这样?
doc 说
有时我们还需要在内联语句处理程序中访问原始 DOM 事件。您可以使用特殊的 $event 变量将其传递给方法:
但是,如您所见,<MyButton /> 已经发出了event 作为有效载荷,我为什么还要使用$event 版本,这让我很困惑。
我的 Codesandbox 链接
【问题讨论】:
标签: javascript vue.js vuejs2