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>
相关推荐
CHB8 分钟前
uni-ai:让你的App快速接入AI
uni-app·deepseek
小徐_23332 天前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
iOS阿玮2 天前
永远不要站在用户的对立面,挑战大众的公知。
uni-app·app·apple
xw52 天前
uni-app中v-if使用”异常”
前端·uni-app
!win !2 天前
uni-app中v-if使用”异常”
前端·uni-app
2501_915918412 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张2 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
00后程序员张3 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬3 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_915106323 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode