Skip to content

17 - 计数器 #2294

Open
Open
@mu-muw

Description

@mu-muw
// 你的答案
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">加</button>
    <button @click="decrement">减</button>
    <button @click="reset">清空</button>
  </div>
</template>
  
<script setup>
import { ref } from 'vue' // 从 vue 中导入 ref

const UseCounterOptions = { // 定义计数器选项
  min: 0,
  max: 0,
}

function useCounter(initialValue = 0, options = {}) { // 定义计数器函数
  const count = ref(initialValue) // 创建一个 ref 变量 count,并将其初始值设置为 initialValue

  function increment() { // 定义加法函数
    if (count.value < options.max) count.value++ // 如果 count 的值小于 options.max,则将其值加一
  }

  function decrement() { // 定义减法函数
    if (count.value > options.min) count.value-- // 如果 count 的值大于 options.min,则将其值减一
  }

  function reset() { // 定义重置函数
    count.value = initialValue // 将 count 的值设置为 initialValue
  }

  return { // 返回一个对象,包含 count、increment、decrement 和 reset 属性
    count,
    increment,
    decrement,
    reset,
  }
}

const { count, increment, decrement, reset } = useCounter(0, { min: 0, max: 10 }) // 使用 useCounter 函数,并将返回的对象赋值给 count、increment、decrement 和 reset 变量
</script>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions