vue3——自己实现计数功能组件封装

时间:2025-03-26 07:33:07
<template> <div class="my-numbox"> <div class="label"> <slot>数量</slot> </div> <div class="numbox"> <a href="javascript:;" @click="toggle(-1)" :class="{notallow: modelValue === 1}">-</a> <input type="text" readonly :value="num"> <a href="javascript:;" @click="toggle(1)" :class="{notallow: modelValue === inventory}">+</a> </div> </div> </template> <script> import { useVModel } from '@vueuse/core' export default { name: 'MyNumbox', props: { modelValue: { type: Number, default: 1 }, inventory: { type: Number, required: true } }, setup (props, { emit }) { // 基于第三方的方法控制数据的双向绑定 const num = useVModel(props, 'modelValue', emit) // 控制商品数据的变更操作 const toggle = (n) => { if (n < 0) { // 减一操作 if ( > 1) { -= 1 } } else { // 加一操作 if ( < ) { += 1 } } } return { num, toggle } } } </script> <style scoped lang="less"> .my-numbox { display: flex; align-items: center; .notallow { cursor: not-allowed; } .label { width: 60px; color: #999; padding-left: 10px; } .numbox { width: 120px; height: 30px; border: 1px solid #e4e4e4; display: flex; > a { width: 29px; line-height: 28px; text-align: center; text-decoration: none; background: #f8f8f8; font-size: 16px; color: #666; &:first-of-type { border-right:1px solid #e4e4e4; } &:last-of-type { border-left:1px solid #e4e4e4; } } > input { width: 60px; padding: 0 5px; text-align: center; color: #666; } } } </style>

相关文章