在我的 Vue.js 应用程序中,子组件发出以下格式的事件:
this.$emit('done-editing', payload)
我的父组件是这样设计的:
<child-component
v-on:done-editing="console.log(data)">
</child-component>
但是当我执行这段代码时,它抛出一个错误提示
TypeError: Cannot read property 'log' of undefined
据我了解,在此范围内未找到 console
对象。 (它最初是在 window
对象上定义的)。我想知道 v-on:event="…"
中 JavaScript 表达式的范围是什么,以及如何在 Vue 模板语法中使用 console.log
。
我知道我可以像下面那样做同样的事情。但是有没有办法在模板表达式中做到这一点?
<template>
<child-component
v-on:done-editing="logMethod(data)">
</child-component>
</template>
<script>
methods : {
logMethod(data) {
console.log(data)
}
}
</script>
最佳答案
v-on
指令中的每个处理程序都“绑定(bind)到此”。这意味着,当您尝试执行以下操作时:
v-on:some-event="console.log('test')"
你实际上在做:
this.console.log('test')
这是无效的,因为 this
指向 Vue 组件实例。这就是您可以这样做的原因:
v-on:some-event="someHandler"
…
methods: {
someHandler() { … }
}
因为 v-on
指令中的表达式自动以 this 为前缀。它调用存在的 this.someHandler
。 v-bind
指令中的表达式也是如此。具体来说,在 the documentation :
[...] all Vue handler functions and expressions are strictly bound to the ViewModel that’s handling the current view [...]
And :
These expressions will be evaluated as JavaScript in the data scope of the owner Vue instance.
关于vue.js - Vue 模板语法表达式的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510112/