3
votes

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 from the Chrome console:

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

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?

5
print your console error messages hereMuhammed Irfan

5 Answers

4
votes

Your methods need to be in your methods section.

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

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

Here is a helpful way I found to add alerts to all your expressions without having to add a method to each Vue component. Adjust the service path to whatever you want.

Create a file called /src/services/utility.js and place in it:

export default {
  methods: {
    //alert wrapper for template debugging
    alert(msg) {
      if (msg === undefined) msg = 'Undefined';
      if (msg === '') msg = 'Empty String';
      alert(msg);
    }
  }
}

Now in your main.js file import the file and set it as a global mixin

import utility from '@/services/utility'
Vue.mixin(utility); 

And a simple button to test it out

<button @click="alert('Meow!')">Make cat speak</button>
0
votes
<template>
  <div class="hello">
    <h1>
        {{ msg }}
    </h1>
    <button v-on:click="showAlert">Click</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      msg: 'Hello World!'
    }
  },
 methods: {
    showAlert: () => {
    alert('test')
  }
 }
}
</script>
0
votes

Instead of just alert('Hello'), you need to do a window.alert('Hello')