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>
相关推荐
中国胖子风清扬2 天前
GPUI 在 macOS 上编译问题排查指南
spring boot·后端·macos·小程序·rust·uni-app·web app
码云数智-园园3 天前
uni-app 实现物流进度跟踪功能:从 UI 到数据驱动的完整方案
ui·uni-app
予你@。4 天前
UniApp + Vue3 实现 Tab 点击滚动定位(微信小程序)
微信小程序·小程序·uni-app
游戏开发爱好者84 天前
完整教程:App上架苹果App Store全流程指南
android·ios·小程序·https·uni-app·iphone·webview
予你@。4 天前
uni-app progress 组件使用详解
uni-app
iOS阿玮4 天前
春节提审高峰来袭!App Store 审核时长显著延长。
uni-app·app·apple
2501_916007475 天前
ios上架 App 流程,证书生成、从描述文件创建、打包、安装验证到上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106325 天前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview
2501_915921436 天前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
云游云记6 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue