简体   繁体   中英

Why my alert function is not working when I 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 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?

Your methods need to be in your methods section .

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

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

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>
<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>

而不仅仅是alert('Hello') ,你需要做一个window.alert('Hello')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM