Boopiester
Boopiester

Reputation: 151

Vue: TypeError: _vm.myFunction is not a function

I am trying to add a simple button in a .vue file to log something to the console with this code:

<template>
  <div>
    <button v-on:click="sayHello()">Click me</button> 
  </div>
</template>
<script>
export default {
  data() {
  },
  methods: {
    sayHello: function () {
      console.log('Hello!')
    }
  },
};

I get the following errors in the console:

TypeError: _vm.sayHello is not a function

and

Property or method "sayHello" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

I have seen some tutorials saying that you should add it to data, but it just says that sayHello() is undefined, or when I define sayHello() in data, it says sayHello() is defined but never used.

I have even tried just doing the following:

<button v-on:click="console.log('Hello!')">Click me</button>

but it gives me this error:

TypeError: Cannot read property 'log' of undefined

Can someone please help me with this? It's probably something super obvious that I haven't tried.

Upvotes: 4

Views: 8128

Answers (2)

Valerii Strilets
Valerii Strilets

Reputation: 318

You didn't close tag <script> after export default { ... }.

And I edited syntax for better readability.

<template>
  <div>
    <button @click="sayHello">Click me</button> 
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },

  methods: {
    sayHello() {
      console.log('Hello!');
    },
  },
};
</script>

For the click events not necessarily a need to call a method with (). But though both variants are correct.

Upvotes: 4

Oleksii Zelenko
Oleksii Zelenko

Reputation: 2701

The error is here

wrong
v-on:click="sayHello()" 


correctly
v-on:click="sayHello" 
<template>
  <div>
    <button @click="sayHello">Click me</button> 
  </div>
</template>
<script>
export default {
  data() {
  },
  methods: {
    sayHello () {
      console.log('Hello!')
    }
  },
}

Upvotes: 1

Related Questions