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>
相关推荐
xshirleyl1 天前
uniapp小兔鲜儿day3
uni-app
Geek_Vison2 天前
2026 跨端框架横评:FinClip、Taro、uni-app、Remax、mPaaS 五款工具技术+业务双维度测评
小程序·uni-app·taro·mpaas·小程序容器
RuoyiOffice2 天前
从 0 到 1 搭建 RuoyiOffice:30 分钟跑通后端+前端+移动端
前端·spring boot·uni-app·开源·oa·ruoyioffice·hrm
Geek_Vison2 天前
APP集成了50多个小程序后,如何搭建一个小程序管理平台来管理这些小程序~
小程序·uni-app·apache·mpaas·小程序容器
梦曦i2 天前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app
梦曦i3 天前
全面解析uni-router v1.2.0功能
前端·uni-app
不如摸鱼去3 天前
Wot UI 2.1.0 发布:ConfigProvider 全局配置能力升级
ui·小程序·uni-app
PedroQue993 天前
uni-router:uni-app路由管理新选择
前端·uni-app
这是个栗子3 天前
微信小程序开发(九)- uni-app微信小程序商城
微信小程序·小程序·uni-app·vue·vuex
中犇科技3 天前
2026商城APP开发公司 TOP5(电商垂直版)
uni-app