B
B
BonBon Slick2020-05-24 15:16:46
typescript
BonBon Slick, 2020-05-24 15:16:46

Invalid handler for event "click": got undefined?

<template v-for="item in [1,2,3,4]">
                        <div @click="this.toggleMenu"                >
                   test
                </div>
            </template>

[Vue warn]: Invalid handler for event "click": got undefined

found in


It gives an error only in the loop, the same method works as it should outside the loop
<div @click="this.toggleMenu"                >
                   test
                </div>


export default class Menu extends Vue {
    toggleMenu() {
        this.isMenuClosed = !this.isMenuClosed;
    }
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-05-24
@BonBonSlick

And you do this {{this}} and see what you have there.
The use of this in templates is not provided, so it is not surprising that it does not work.
Your template is converted by the compiler into something like this render function:

function anonymous() {
  with (this) {
    return _c('div', [
      _l(
          ([1, 2, 3, 4]),
          function (item) {
            return [
              _c(
                  'div',
                  {on: {"click": this.toggleMenu}},
                  [_v("\n                   test\n                ")]
              )
            ]
          }
      )
    ], 2)
  }
}
As you can see, iteration of item happens inside another function that sets a different context (none).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question