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>
相关推荐
RuoyiOffice1 天前
2026 企业定制开发选型:从零开发、低代码、SaaS 与 RuoYi Office 怎么选?
spring boot·uni-app·开源·saas·oa·定制化·ruoyioffice
三天不学习1 天前
【超详细】Vue3+UniApp+.NET8集成腾讯云IM即时通信全攻略
uni-app·.net·腾讯云·im·即时通信
于先生吖2 天前
前后端分离人事招聘项目,校招宣讲预约+社招双向撮合功能架构设计教程
java·开发语言·uni-app
QQ_5110082852 天前
uniapp微信小程序网上饰品商城售卖系统php python物流
微信小程序·uni-app·php
2501_915909062 天前
深入解析Mock.js:功能、应用及实战案例,提升前端开发效率
android·ios·小程序·https·uni-app·iphone·webview
于先生吖2 天前
前后端分离体育服务项目,场馆计费+线下赛事排行小程序部署开发教程
java·小程序·uni-app
蜡台2 天前
Uniapp 实现预览pdf 文件
pdf·uni-app·pdfh5
不想吃饭e2 天前
uniapp-图片,视频上传组件封装
java·uni-app·音视频
2501_916007472 天前
不用 Mac 也可以 Windows下管理iOS描述文件的非Xcode完整指南
android·ios·小程序·https·uni-app·iphone·webview
于先生吖3 天前
UniApp搭配Java后端实现到店预约上门指派,订单状态流转与结算开发教程
java·开发语言·uni-app