1

This what I'm about to ask was actually raised as an issue on a simple getting started tutorial demo that I wrote.

A simple Vue CLI started app vue init webpack giphy-search.

This code gives undefined when you click on the button:

<template>
<div class="hello">
    <input name="search" v-model="searchTerm">
    <button @click="performSearch">Search</button>
    <h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
    return {
    msg: "Welcome to GiphySearch",
    searchTerm: "testing"
    };
},
methods: {
    performSearch: () => {
        console.log(this.searchTerm);
    }
}
};
</script>

And this one works fine:

<template>
<div class="hello">
    <input name="search" v-model="searchTerm">
    <button @click="performSearch">Search</button>
    <h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
    return {
    msg: "Welcome to GiphySearch",
    searchTerm: "testing"
    };
},
methods: {
    performSearch: function() {
        console.log(this.searchTerm);
    }
}
};
</script>

The problem is on this line:

performSearch: () => {

If I write it like this:

performSearch: function () {

it will work as expected.

However, to be perfectly honest, I'm puzzled, as I thought the () => would get transpiled correctly. I even checked out with npm run build and opened the built code to see if the code is transpiled - it was, but still got the undefined log in the console when I clicked on the button.

So, dear Vue.js experts, please help me out here to understand what's going on. Thanks!

Nikola
  • 14,888
  • 21
  • 101
  • 165
  • It's based on how arrow functions handle `this`. Arrow functions retain their reference to `this` in the context it was called when using higher-order functions or when used in properties, while `function()` syntax doesn't and will use `this` in the context of wherever it is called. – RecyclingBen Mar 31 '18 at 20:57

0 Answers0