I have a very simple vue components that looks like this:
<template>
<div class="incrementor">
<p v-text="counter"></p>
<button v-on:click="increment()">Increment</button>
</div>
</template>
<script lang="ts" src="../scripts/incrementor.ts"></script>
<style lang="scss" src="../styles/incrementor.scss"></style>
This is my 'incrementor.ts' script file:
import { Component, Vue, Prop } from "vue-property-decorator";
@Component({})
export default class Incrementor extends Vue {
private counter: number = 0;
increment = () => {
this.counter++;
};
}
My problem is that when i click the button i can see the counter increasing in the console but the component doesn't re-render so the 'counter' text in the browser stays at 0.
I know i can do it like this:
<template>
<div class="incrementor">
<p v-text="counter"></p>
<button v-on:click="counter++">Increment</button>
</div>
</template>
<script lang="ts" src="../scripts/incrementor.ts"></script>
<style lang="scss" src="../styles/incrementor.scss"></style>
And it works but i want to be able to use my own methods for this.
Few issues here:
Instead of calling the function directly, we need to pass the function reference like:
<button v-on:click="increment">
Next, as mentioned in the docs, component methods can be declared as instance methods like:
increment() {
this.counter++;
};
After implementing these changes, the increment counter will work fine.