0

I'm trying to access the instance methods/data through a triggered method inside a custom registered Vue component.

Below a basic example:

Vue.component('example-component', {
        template: `<div>
                        <h2>Count: {{count}}</h2>
                        <button class="btn btn-primary" v-on:click="increment()">Increment</button>
                    </div>`,
        data: () => {
            return {
                count: 0
            }
        },
        methods: {
            increment: () => {
                console.log("Click!");
                console.log("Current count: ", this.count);
                this.count++;
                console.log("New count: ", this.count);
            },
            decrement: () => {
                // other function
            }
        },
        mounted: () => {
            console.log("Example component mounted!");
        }
    });

Results:

Example component mounted!
Click!
Current count:  undefined
New count:  NaN

As you might notice the property 'count' has been loaded during the component mount and is available/rendered inside the HTML. The method 'increment()' has also been triggered. However, 'this.count' seems to be unreachable like possible other methods (e.g. 'this.decrement()') which will throw a TypeError this.decrement is not a function.

Any suggestions if this approach is even possible?

PS. I'm aware of the default approach via a .vue file registery like:

Vue.component('example-component', require('./components/ExampleComponent.vue').default);
1
  • The methods and hooks such as mounted, etc, shouldn't be arrow functions Commented Mar 3, 2021 at 21:15

2 Answers 2

1

Explanation from the official docs:

Vue automatically binds the this value for methods so that it always refers to the component instance. This ensures that a method retains the correct this value if it's used as an event listener or callback. You should avoid using arrow functions when defining methods, as that prevents Vue from binding the appropriate this value.

The answer above by Phoenix seems to be valid, and I can only add that you can write the functions in a short form too like:

increment() { ... },
decrement() { ... }

which looks nicer in my opinion, although there is a slight difference.

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

1 Comment

Thank you for your comment. It works and looks nicer indeed!
0

Arrow functions don't bind with this. Use normal functions instead for your methods.

increment: function() { ... },
decrement: function() { ... }

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.