mattymil
mattymil

Reputation: 143

VueJS TypeError cannot read property of

OK, so I haven't worked with Vue in probably over 2 years and I am giving myself a refresher. I feel really silly about asking such a simple question but I just can't figure out what I am doing wrong. I have a simple counter example where I am calling v-on:click(call my method). The method called counter simply does this.count++. I verified that the method works because I can call console.log or alert within it with no issues. But when I try to increment the counter it returns "Error in v-on handler: "TypeError: Cannot read property 'count' of undefined". My source code is as follows:

<template lang="pug">
    b-container(id="cont")
        b-button(v-on:click="counter") Click Me
        p {{count}}

</template>

<script>
    export default {
        data: () => {
            return {
                count: 0
            }        
        },
        methods: {
            counter: () => {
                this.count++
            }
        }
        
    }
</script>

<style>
#cont {
   margin-top: 10px
}
</style>

Upvotes: 0

Views: 1175

Answers (3)

Benjamin Beganović
Benjamin Beganović

Reputation: 1168

If you are willing the use arrowed version, use like this:

data: () => {( counter: 0 )},

Otherwise refer to the previous answers =)

Upvotes: 0

Khalid Dabjan
Khalid Dabjan

Reputation: 2797

I think this has to do with the fact that you are using arrow functions to define your methods, so instead try this:

<script>
export default {
    data(){
        return {
            count: 0
        }        
    },
    methods: {
        counter(){
            this.count++
        }
    }

}
</script>

Because arrow functions are not bound to this, so this will be undefined inside of an arrow function.

Upvotes: 3

awagen
awagen

Reputation: 236

try this:

data() {
    return {
       count: 0
    }
}

e.g without making that a method.

Upvotes: 0

Related Questions