2

I'm trying to learn VueJS. I've made my first vue and I'm testing the directives. Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Partie 1 Chapitre 3 - Vue Mart</title>
</head>
<body>
<div id="app">
 
  <button v-on:click="alert('hello')">Cliquez ici !</button>

</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      costOfApples: 5,
      costOfBananas: 2,
      costOfCoconuts: 8,

      favoriteColor: 'rose'
    },
    //Propriétés calculées
    computed: {
      totalAmount() {
        return this.costOfApples + this.costOfBananas + this.costOfCoconuts
      },
      label() {
        return ': '+ this.favoriteColor
      }
    }
  })
</script>

</body>
</html>

When I click my button I get this error:

TypeError: alert is not a function
[Vue warn]: Error in v-on handler: "TypeError: alert is not a function"
[Vue warn]: Property or method "alert" 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. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)

I really don't know where to start looking. To me, my code seems okay. Thanks for your help

tony19
  • 125,647
  • 18
  • 229
  • 307
Akame14
  • 151
  • 1
  • 2
  • 12

2 Answers2

3

you should define alert in your methods

methods(){
   alert(){
       // do something      
   }
}
arman amraei
  • 175
  • 1
  • 5
  • Okay I see, I thought it would execute like the alert method. but then if I want to reproduce the behavior of the alert method how can I do this? I'm following a tutorial using alert like and they did not define it in their methods, that's why I was asking – Akame14 Aug 14 '20 at 08:53
  • 1
    Edit: I called showColor like that `` and then I defined a method `showColor (){ alert('hello')}` and it worked. THough, I don't know why it's not working when I directly do `` Is it because of the Directives? Thanks! – Akame14 Aug 14 '20 at 08:59
  • 1
    @click="()=>{alert('test')}" this way you could use js alert directly – arman amraei Aug 14 '20 at 08:59
0

I am doing the same tutorial and they indeed do not explain it.

Here is how I did it :

    <script>
        const app = new Vue({
            el: "#app",
            data: {
                //some stuff
            },
            computed: {
                // some other stuff
                }
            },
            methods: {
                alert(message) {
                    alert(message)
                }
            }
        })
    </script>

This is a VueJS v2 tutorial, i think this is not needed in v3