aBloomer aBloomer - 3 months ago 19
Javascript Question

Why my alert function is not working when click on button in Vue.js

This is my index.html

<body>
<app></app>
</body>


This is my main.js

import Vue from 'vue'
import App from './App'

new Vue({
el: 'body',
components: { App }
})


This is my App.vue

<template>
<div id="app">
<img class="logo" src="./assets/logo.png">
<hello></hello>
</div>
</template>

<script>
import Hello from './components/Hello'

export default {
components: {
Hello
}
}
</script>


and This is my Hello.vue

<template>
<div class="hello">
<h1>
{{ msg }}
</h1>
<button v-on:click="showAlert">Click</button>
</div>
</template>

<script>
export default {
data () {
return {

msg: 'Hello World!'
}
},
showAlert: () => {
alert('test')
}
}
</script>


Here is the error message form chrome console

[Vue warn]: v-on:click="showAlert" expects a function value, got undefined (found in component: <hello>)


I can see "Hello world!" on my screen and the button but nothing happened when I click on it.

I suppose I will have "test" alert message.

Did I do something wrong?

Answer

Your methods need to be in your methods section.

<script>
export default {
  data () {
    return {

      msg: 'Hello World!'
    }
  },
  methods: {
    showAlert: () => {
      alert('test')
    }
  }
}
</script>
Comments