uniapp|微信小程序 实现输入四位数 空格隔开

javascript 复制代码
<template>
  <page-meta :page-style="cssVar"></page-meta>
  <view class="container">
    <u-navbar
      title="优惠券兑换"
      placeholder
      bgColor="#fff"
      :autoBack="true"
      :titleStyle="{
        fontFamily: 'SourceHanSansCN-Medium',
      }"
    ></u-navbar>
    <view class="main">
      <view class="image-container">
        <image class="img-item" src="@/assets/images/meituan.png" />
        <image class="img-item" src="@/assets/images/douyin.png" />
        <image class="img-item" src="@/assets/images/dazhongdianping.png" />
      </view>
      <view class="form-container">
        <view class="input-container">
          <u-input
            type="number"
            :modelValue="codeValue"
            placeholder="输入美团/抖音/大众点评券码"
            @change="valueChange"
            clearable
          />
        </view>
        <u-button
          :disable="!codeValue"
          @click="handleConfirm"
          class="form-btn"
          text="确认修改"
          :customStyle="btnStyle"
        ></u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue';
const codeValue = ref('');

const handleConfirm = async () => {
  if (!codeValue.value) return;
  uni.showLoading({ title: '兑换中', mask: true });
  const value = codeValue.value.replace(/\s/g, '');
  const params = {
    code: value,
  };
  const { code } = await couponUserCoinCertificate(params); // 你的兑换接口
  if (code === '0') {
    uni.showToast({ title: '兑换成功' });
  }
};

const btnStyle = computed(() => {
  return { background: !codeValue.value ? '#CCCCCC' : 'var(--main-color)' };
});

// 实现空格的关键
function valueChange(e) {
  // 先移除所有空格
  var noSpacesValue = e.replace(/\s/g, '');
  // 然后每四个字符添加一个空格
  var formattedValue = noSpacesValue.replace(/(.{4})/g, '$1 ').trim();
  // 移除最后一个空格(如果存在)
  formattedValue = formattedValue.replace(/\s+$/, '');
  codeValue.value = formattedValue;
}
</script>
相关推荐
felipeas1 天前
uni-app day1
uni-app·notepad++
前端后腿哥1 天前
UNIAPPX UTS插件Widget开发完整教程(Android版)
前端·uni-app
黄同学real2 天前
uni-app 真机调试:手动代理环境下访问内网 API 的解决方案
uni-app
Hoshizola2 天前
uniapp与蓝牙设备连接详细步骤
前端·uni-app
优雅格子衫2 天前
uniapp 拍照相册选取后超级好用的裁剪组件,增加水印完全自定义
开发语言·前端·javascript·uni-app·vue
路光.2 天前
uniapp中解决webview在app中调用,有过渡空白问题,增加过渡动效
uni-app·vue·app·uniapp
linlinlove22 天前
前端uniapp、后端thinkphp股票系统开发功能展示、代码披露、HQChart
前端·uni-app·echarts·thinkphp·hqchart·配资·deepseek选股票
2501_915909062 天前
深入理解HTTPS中间人抓包技术原理与实战指南
网络协议·http·ios·小程序·https·uni-app·iphone
2501_916007473 天前
iOS应用性能优化全面指南:从内存管理到工具使用
android·ios·性能优化·小程序·uni-app·iphone·webview
巴博尔3 天前
UNIAPP中NVUE页面 动画
android·前端·javascript·ios·uni-app