1. 程式人生 > 程式設計 >Vue實現控制商品數量元件封裝及使用

Vue實現控制商品數量元件封裝及使用

控制商品數量元件的封裝及使用,供大家參考,具體內容如下

要實現效果

Vue實現控制商品數量元件封裝及使用

控制商品數量元件封裝 Numbox

<template>
    <div class="xtx-numbox">
    <div class="label">
      <slot />
    </div>
    <div class="numbox">
      <a href=":;" @click='toggle(-1)'>-</a>
      <input type="text" readonly :value="num">
      <a href="script:;" @click='toggle(1)'>+</a>
    </div>
  </div>
</template>
<script>
import { useVModel } from '@vueuse/core'

export default {
  name: 'XtxNumbox',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 (num.value > 1) { num.value -= 1 www.cppcns.com } } else { // 加一操作 if (num.value < 10) { num.value += 1 } } } return { num,toggle } } } </script> <style scoped lang="less"> .xtx-numbox { display: flex; align-items: center; .label { width: 60px; color: #999; padding-left: 10px; } .numbox { width: 120px; height: 3www.cppcns.com
0px; 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; http://www.cppcns.com
padding: 0 5px; text-align: center; color: #666; } } } </style>

在父元件使用

<Numbox v-model='num' >數量</XtxNumbox>
setup(){
 // 商品的數量  // 預設值是1
  const num=ref(1)
  return {
    num 
  }
}

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