'How to properly call a method on a Vue component

I'm quite new to using Vue2. I'm using the Vue CLI so I just follow the structure of what's generated from it.

What I'm trying to do is submit form data. But I keep getting this warning and error:

[Vue warn]: Property or method "onSubmit" 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.

and

Uncaught TypeError: _vm.onSubmit is not a function

Here's the relevant code from my .vue file:

<script>
import { contact } from './my/exports';

export default {
  name: 'Contact',
  data () {
    return {
      form: {
        name: ''
      }
    }
  },
  method: {
    onSubmit: function () {
      console.log('My Logic Here')
    }
  }
}
</script>

and

<template>
  <form @submit.prevent="onSubmit">
    <input type="text" placeholder="Text here..." v-model="form.name">
    <button type="submit">Submit</button>
  </form>
</template>

I can't seem to call the method from my instance. To me, it sounds like I need to make use of the lifecycle hooks? Or am I wrong? I can't find any examples of calling methods from a button click. Most of them are usually used on initialization of an instance.

Can anyone point me in the right direction? Thanks!



Solution 1:[1]

As already pointed out, the correct component property for Method Handlers must be methods and not method.

However, if others have this problem and stumble upon this, I'm also going to explain a problem I just resolved in some code I was writing.

For me this was happening on a @click="" handler inside of some code that was using Teleport and a custom Component and I thought that was all related.

However, after many hours of debugging, I discovered that the only problem I had was that I simply misplaced a closing brace } character that terminated the methods property declaration prematurely!!

So if you encounter an event handler method is not defined type of problem in Vue, and all else looks right, verify that the component methods property is declared correctly and not terminated prematurely.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ray Cardillo