【发布时间】:2021-09-23 06:46:20
【问题描述】:
首先,我不确定这是一个 Vue 问题还是只是一个与 JavaScript 相关的问题。 我写了一些代码终于可以工作了,但我不知道为什么。也许你能启发我。
我创建了一个“对话窗口”组件。这是一个简单的(模态)对话框,它以函数为参数。如果用户单击确定,则调用该函数 - 例如“您真的要删除该文件吗?”取消或确定。
我传递给组件的函数有时本身有一个参数。 所以我想将已经参数化的函数作为参数传递给我的组件。 我通过将函数包装在箭头函数中来实现这一点,该箭头函数返回然后可以调用的参数化函数。
这个概念在纯 JS 中的思路是这样的:
//the function to be finally executed
function say(message) {
document.getElementById("output").innerHTML = message;
}
//the parameterized function inside of an arrow function (as a variable)
const sayhelloworld = () => say("hello world");
//finally I call the arrow function which
//returns the parameterized function and calls this one as well
function start() {
sayhelloworld()(); //this is the core of my question: the double brackets!
}
所以我需要双括号。第一个 () 返回内部的函数,第二个 () 调用它。 它确实像这样工作: https://codepen.io/keztur/pen/powaLJN
现在让我们转向 vue:
我用事件总线打开我的对话框组件(很抱歉)并传递一个包含函数参数的参数对象。 (我使用 Vue 3 - 所以我的 EventBus 对象后面实际上是 'mitt' 库:https://github.com/developit/mitt)
//component calling the dialog and passing the function parameter
//(as a part of a parameter object)
EventBus.emit("OpenDialog", {
header: "Delete file",
body: "Do you really want to delete that file?",
function: () => this.Delete(file_id)
});
模态组件:
data() {
return {
show: false,
ModalProps: {
header: "",
body: "",
function: ""
}
};
},
//inside of the modal component this function is called
//if the user clicks any of the two buttons (cancel or OK)
methods: {
clicked(button) {
if (button === 'ok' && typeof this.ModalProps.function === 'function') {
this.ModalProps.function(); //why does this work ...
//this.ModalProps.function()(); //...but not this?
//the second line does call the function but also throws an error afterwards
}
this.show = false; //modal is closed
}
},
... etc.
所以起初我在上面的 JS 示例中使用双括号。并且该函数被正确调用,但第二个“执行”备份显然引发了错误:
[Vue warn]: Unhandled error during execution of native event handler
at <Modal>
at <App>
但是由于我删除了第二个括号,所以一切正常。
所以我的问题是:为什么在 Vue 中我的箭头函数中的函数会立即被调用,而不是通过引用返回?
【问题讨论】:
标签: javascript vue.js vue-component