-1

here is the code:

<template>
  <div id="app">
      <button
        @click="() => this.search()"
      >btn1</button>

      <button
        @click="() => this.search1()"
      >btn2</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    search: () => {
      console.log(this);
      //debugger
    },
    search1: function() {
      console.log(this);
      //debugger
    },
  },
};
</script>

when I click 'btn1' , the console show "undefined".

when click 'btn2', the console show vuecomponent.

I'm so confuse why 'this' is undefined?


Then I found stranger thing,

when use debugger for breakpoint debugging where the console prints ‘undefined’

I can see the value of ‘this’ again. Why?

see:

strange thing scrennshot

Rico Lee
  • 11
  • 3

1 Answers1

0

It's explained in the docs:

Note that you should not use an arrow function to define a method (e.g. plus: () => this.a++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.a will be undefined.

tony19
  • 125,647
  • 18
  • 229
  • 307
Decade Moon
  • 32,968
  • 8
  • 81
  • 101
  • thank you :) but when use debugger for breakpoint debugging where the console prints ‘undefined’, I can see the value of ‘this’ again, can you explain it? thanks, see:[https://i.stack.imgur.com/0Jxzi.png](https://i.stack.imgur.com/0Jxzi.png) – Rico Lee Jan 26 '22 at 07:32
  • That should not happen. `this` really is `undefined`. Maybe try viewing the script source without the source map. – Decade Moon Jan 26 '22 at 09:58