0

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>

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

try this:

data() {
    return {
       count: 0
    }
}

e.g without making that a method.

Comments

0

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

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

Otherwise refer to the previous answers =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.