1. 程式人生 > 程式設計 >vue3封裝計時器元件的方法

vue3封裝計時器元件的方法

背景

在一些商城類中開啟商品詳情都會有一個計數器來選擇購買的數量,這樣的計時器不僅會在商品詳情頁面顯示還會在購物車裡面有,那就可以把計時器封裝成元件,以便於更好的複用以及後期維護

落地程式碼

<template>
  <div class="xtx-numbox">
    <div class="label"><slot /></div>
    <div class="numbox">
      <a href=":;" @click="handleSub(-1)">-</a>
      <input type="text" readonly :value="num" />
      <a href="script:;" @clickhttp://www.cppcns.com
="handleSub(1)">+</a> </div> </div> </template> <script> // 第三方方法 useVModel 來實現雙向繫結 import { useVModel } from '@use/core' export default { name: 'XtxNumbox',props: { modelValue: { type: Number,default: 1 } },setup(props,{ emit }) { // useVModel 方法接收三個引數, // 引數一:自定義屬性 props 接收父元件傳遞過來的通過 v-model 雙向繫結的資料 // 引數二:props 裡面需要傳遞的資料 // 引數三:emit 繫結的資料需要通過 emit 事件通知父元件
const num = useVModel(props,'modelValue',emit) const handleSub = n => { if (n < 0) { num.value -= 1 if (props.modelValue === 1) { num.value = 1 } } else { num.value += 1 } } return { handleSub,num } } } </script> <style scoped lang="less"> .xtx-numbox { dispQHdknoI
lay: flex; align-items: center; .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; 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>

使用

<XtxNumbox v-model="num">數量客棧</XtxNumbox>

效果

vue3封裝計時器元件的方法

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。