Search code examples
javascriptvue.jsconsole.logarrow-functions

Why is "console" not defined in an inline function that handles an event from a component?


I wrote a component my-component that emits the message my-message via this.$emit('my-message').

In order to act on this message, I tried to use

<my-component @my-message="()=>console.log('hello')" />

When looking at the console, I see the warning (and then error)

Property or method "console" is not defined on the instance but referenced during render

Having made the mistake many times, I presume that the error comes from the context using fat arrows (this vs that = this before) but here I am lost.

console is exposed as Window.console but Window generates the same error if I use the full form.


Solution

  • That will not work in Vue.

    Pass a method name instead

    <template>
      <button @click="log('test')">
        test
      </button>
    </template>
    
    <script>
    import { defineComponent } from "vue";
    export default defineComponent({
      methods: {
        log(value) {
          console.log(value)
        }
      }
    });
    </script>