4

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!')
    }
  },
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.