Skip to content

17 - useCounter #2279

Open
Open
@woojerry

Description

@woojerry
<script setup lang="ts">
import { ref } from "vue";

interface UseCounterOptions {
  min?: number;
  max?: number;
}

/**
 * Implement the composable function
 * 1. inc (+)
 * 2. dec (-)
 * 3. reset
 * 4. min & max opotion support
 * Make sure the function works correctly
 */
function useCounter(initialValue = 0, options: UseCounterOptions = {}) {
  const count = ref(initialValue);
  const { min, max } = options;

  const inc = () => {
    if (max && count.value < max) {
      count.value += 1;
    }
  };

  const dec = () => {
    // 0 is falsy in JS
    if (min !== undefined && count.value >= min) {
      count.value -= 1;
    }
  };

  const reset = () => {
    count.value = initialValue;
  };

  return { count, inc, dec, reset };
}

const { count, inc, dec, reset } = useCounter(0, { min: 0, max: 10 });
</script>

<template>
  <div>
    <div>Count: {{ count }}</div>
    <div>
      <button @click="inc">increase</button>
      <button @click="dec">decrease</button>
      <button @click="reset">reset</button>
    </div>
  </div>
</template>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions