vue.js - Vue 模板语法表达式的范围

标签 vue.js vue-component

在我的 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.someHandlerv-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/

相关文章:

javascript - VueJS 复选框更新

vue.js - 看。如何在创建的元素中获取 "key"属性的值

javascript - 在加载 vue.js 时运行组件方法

vue.js - 在 VueJS 中使用第三方组件

vue.js - vue单文件组件报错模板元素未找到或为空

javascript - 在 Vue 中渲染只读内容的最佳方法

javascript - Vue : template can't be keyed, 但不能用 div 替换模板 - 需要没有包装 div 元素的 v-for,嵌套的 v-for 循环

vuejs2 - 在 Vuetify 中使用自定义主题并将颜色变量传递给组件

javascript - 如何在组件 VueJS 中初始化小部件?

vue.js - 在 Vue js 中从父组件更新子组件