0

I'm just practicing some Vue3 props handling and I noticed something interesting.

I have this useCounter function that simply takes a value and returns a new one.

interface Counter {
    incrementCounter: () => number;
    decrementCounter: () => number;
}

export function useCounter(): Counter {
    const incrementCounter = (num: number): number => {
        return ++num;
    };

    const decrementCounter = (num: number): number => {
        return --num;
    };

    return { incrementCounter, decrementCounter };
}

I'm using that method in a Adder component which receives the counter prop from the parent.

<template>
    <button @click="handleClick">Increment</button>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useCounter } from "../functions/useCounter"

export default defineComponent({
    props: {
        counter: {
            type: Number,
        }
    },
    setup(props, { emit }) {
        const { incrementCounter } = useCounter()

        const handleClick = (): void => {
            emit('update:counter', incrementCounter(props.counter))
        }

        return { handleClick }
    }
})

</script>

My real question is why doing ++num works but num++ doesn't? I ask because I was going to give up on this approach until I decided to experiment, but can't understand why it works

Riza Khan
  • 2,712
  • 4
  • 18
  • 42
  • `++x` - pre-increment - increment *first*, then return the value; `x++` - post-increment - return the value *first*, then increment. – VLAZ Sep 28 '21 at 19:56
  • I guess I was asking in the context of Vue, but it does make sense – Riza Khan Sep 28 '21 at 19:57
  • 1
    Vue doesn't alter anything, since Vue is still simply running JS. If you have `foo = x => x++` then `foo(3)` returns `3` and increments something that's never used again. Basic JS. – VLAZ Sep 28 '21 at 19:58

0 Answers0