vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择

这篇具有很好参考价值的文章主要介绍了vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

vue3+ts 基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及单列选择


自我记录

1.先上效果图

vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue

vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue

vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue

直接上代码

2.代码展示

2.1 组件

src\components\hbcy-popup.vue

<script setup lang="ts">
import type { Item, PopupType } from '@/types/addInfo'
import { formatDate, parseDate } from '@/utils'
import { onMounted } from 'vue'
import { ref } from 'vue'

const props = defineProps<{
  popupTitle: string
  type: PopupType
  data?: Item[] // 展示数据List
  selectData: string | number // 默认显示 '2023-8-24' || 0
}>()
const emit = defineEmits<{
  (e: 'confirm-popup', params: string | number): void
  (e: 'close-popup'): void
}>()

// 创建选择区间 参考uni文档
const date = new Date()
// 年月日
const TYPEYY_MM_DD = props.type === 'year' || props.type === 'month' || props.type === 'day'
// 月日
const TYPEMM_DD = props.type === 'month' || props.type === 'day'
const TYPEYY = props.type === 'year'
const TYPEMM = props.type === 'month'
const TYPEDD = props.type === 'day'
const TYPESingle = props.type === 'single'
const years = TYPEYY_MM_DD
  ? Array.from({ length: date.getFullYear() - 1989 }, (_, index) => 1990 + index)
  : []
const months = TYPEMM_DD ? Array.from({ length: 12 }, (_, index) => index + 1) : []
const days = TYPEDD ? Array.from({ length: 31 }, (_, index) => index + 1) : []
// 处理默认展示的时间
const defaultDate = TYPEYY_MM_DD ? parseDate(props.selectData as string, props.type) : []
// 单列数据
const singleList = ref(TYPESingle ? props.data : [])
const singleSelect = ref<number>((props.selectData as number) || 0)
// 确保默认时间
const year = ref<number>(defaultDate[0])
const month = ref<number | undefined>(defaultDate[1])
const day = ref<number | undefined>(defaultDate[2])
// 区分日期展示
let showValueList: number[] = []
// 展示日期的选中时间
if (TYPEDD) {
  showValueList = [
    years.indexOf(defaultDate[0]),
    months.indexOf(defaultDate[1]!),
    days.indexOf(defaultDate[2]!),
  ]
} else if (TYPEMM) {
  showValueList = [years.indexOf(defaultDate[0]), months.indexOf(defaultDate[1]!)]
} else if (TYPEYY) {
  showValueList = [years.indexOf(defaultDate[0])]
} else if (TYPESingle) {
  showValueList = [singleSelect.value]
}
const valueList = ref<number[]>()
onMounted(() => {
  // 确保回显的value 在 页面渲染之后
  valueList.value = showValueList
})

// 切换事件
const bindChange: UniHelper.PickerViewOnChange = (e) => {
  const val = e.detail.value

  if (TYPEYY_MM_DD) {
    year.value = years[val[0]]
    month.value = months[val[1]]
    day.value = days[val[2]]
  } else {
    // 单列
    singleSelect.value = val[0]
  }
}
// 确定按钮
const onClickConfirmPopup = (): void => {
  if (TYPEYY_MM_DD) {
    emit('confirm-popup', formatDate(year.value, month.value, day.value))
  } else {
    // 单列
    emit('confirm-popup', singleSelect.value)
  }
  onClosePopup()
}
// 关闭弹出层
const onClosePopup = (): void => {
  emit('close-popup')
}
const { safeAreaInsets } = uni.getSystemInfoSync()
</script>

<template>
  <view class="selectBox">
    <view class="selectTitle">
      <text class="cancel" @click="onClosePopup">取消</text>
      <text class="title">{{ '选择' + popupTitle }}</text>
      <text class="cancel ok" @click="onClickConfirmPopup">确定</text>
    </view>
    <block v-if="TYPEYY_MM_DD">
      <picker-view
        :immediate-change="true"
        indicator-class="indicatorClass"
        :value="valueList"
        @change="bindChange"
        class="picker-view"
      >
        <picker-view-column>
          <view class="item" v-for="(item, index) in years" :key="index">{{ item }}</view>
        </picker-view-column>
        <picker-view-column v-if="TYPEMM_DD">
          <view class="item" v-for="(item, index) in months" :key="index">{{ item }}</view>
        </picker-view-column>
        <picker-view-column v-if="TYPEDD">
          <view class="item" v-for="(item, index) in days" :key="index">{{ item }}</view>
        </picker-view-column>
      </picker-view>
    </block>
    <!-- TODO -->
    <block v-else>
      <picker-view
        :immediate-change="true"
        indicator-class="indicatorClass"
        :value="valueList"
        @change="bindChange"
        class="picker-view"
      >
        <picker-view-column>
          <view class="item" v-for="item in singleList" :key="item.key">{{ item.value }}</view>
        </picker-view-column>
      </picker-view>
    </block>
    <!-- 修复启用:safeArea="true" 时 圆角不好实现问题,现在是自己做的适配-->
    <view :style="{ height: safeAreaInsets?.bottom + 'px' }" style="width: 100%" />
  </view>
</template>
<style lang="scss" scoped>
::v-deep.indicatorClass {
  height: 100rpx;
}
.picker-view {
  width: 750rpx;
  height: 500rpx;
  margin-top: 20rpx;
}
.item {
  line-height: 100rpx;
  text-align: center;
}
.selectBox {
  width: 100%;
  height: fit-content;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  .selectTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    font-size: 32rpx;
    .title {
      font-size: 32rpx;
    }
    .cancel {
      width: 160rpx;
      text-align: center;
      color: #ff976a;
      font-size: 32rpx;
    }
    .ok {
      font-size: 32rpx;
      color: #07c160;
    }
  }
}
</style>

2.2 公共方法处理日期

src\utils\index.ts

// 将 yyyy-mm-dd 的字符串 2023-08-24 => [2023,8,24] || [2023,8] || [2023]
export function parseDate(dateString: string, type: string): [number, number?, number?] {
  const date = dateString ? new Date(dateString) : new Date()
  const year = date.getFullYear()
  const month = type === 'day' || type === 'month' ? date.getMonth() + 1 : undefined
  const day = type === 'day' ? date.getDate() : undefined
  return [year, month, day]
}

// 将数字格式的年、月、日转换成格式为 yyyy-mm-dd 的字符串 || yyyy-mm || yyyy
export function formatDate(year: number, month?: number, day?: number): string {
  const formattedMonth = month !== undefined ? (month < 10 ? `0${month}` : `${month}`) : ''
  const formattedDay = day !== undefined ? (day < 10 ? `0${day}` : `${day}`) : ''
  return `${year}${formattedMonth ? `-${formattedMonth}` : ''}${
    formattedDay ? `-${formattedDay}` : ''
  }`
}
// 获取当前年月日并返回yyyy-mm-dd格式
export function getCurrentDate(): string {
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
  const day = currentDate.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

2.3 使用组件(全局自动导入的情况)

全局自动导入看(https://blog.csdn.net/zhgweb/article/details/132499886?spm=1001.2014.3001.5502 第11标题
没有配置全局自动导入的需要自己手动引入!
src\pages\test\index.vue文章来源地址https://www.toymoban.com/news/detail-685845.html

<script setup lang="ts">
import type { Ref } from 'vue'
import { ref } from 'vue'
import { getCurrentDate } from '@/utils'
type Item = {
  key: number | string
  value: string
}

// 日期相关
const isShowPopop = ref(false)
// 弹出层实例
const refSelectDialog: Ref<UniHelper.UniPopup | null> = ref(null)
const dateTime = ref(getCurrentDate()) // 默认显示当前时间
// 单列相关
let list = [
  { key: 1, value: '最高' },
  { key: 2, value: '最低' },
  { key: 3, value: '自定义' },
]
const singleList = ref<Item[]>(list)
const singleSelect = ref(0)
const isShowSingPopop = ref(false)
const selectItem = ref<Item>(singleList.value[singleSelect.value]) // 默认选中

// 打开日期弹窗 or 单列
const onClickPopup = (type?: string) => {
  refSelectDialog.value!.open()
  if (type === 'single') {
    isShowSingPopop.value = true
  } else {
    isShowPopop.value = true
  }
}
// 关闭弹窗
const onClosePopup = () => {
  refSelectDialog.value!.close()
  isShowPopop.value = false
  isShowSingPopop.value = false
}
// 确定日期弹窗
const onConfirmPopup = (val: string | number, type: string) => {
  if (type === 'single') {
    singleSelect.value = val as number
    selectItem.value = singleList.value[singleSelect.value]
    console.log(selectItem.value, 'singleSelect')
  } else {
    dateTime.value = val as string
    console.log(dateTime.value, 'dateTime.value')
  }
}
</script>

<template>
  <view class="test-page">
    <!-- 使用组件 -->
    <uni-popup
      ref="refSelectDialog"
      type="bottom"
      :maskClick="false"
      :isMaskClick="false"
      :safeArea="false"
      :close="onClosePopup"
    >
      <hbcy-popup
        v-if="isShowPopop"
        popup-title="日期"
        type="day"
        :select-data="dateTime"
        @confirm-popup="onConfirmPopup($event, 'dateTime')"
        @close-popup="onClosePopup"
      />
      <hbcy-popup
        v-if="isShowSingPopop"
        popup-title="社保基数"
        type="single"
        :data="singleList"
        :select-data="singleSelect"
        @confirm-popup="onConfirmPopup($event, 'single')"
        @close-popup="onClosePopup"
      />
    </uni-popup>
  </view>
</template>
<style lang="scss" scoped>
.test-page {
  .item-date {
    width: 300rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    border: 1rpx solid #999;
    font-size: 28rpx;

    &-placeholder {
      color: #999;
    }

    &-txt {
      color: #333;
    }
  }
}
</style>

3.注意事项

3.1refSelectDialog

// 弹出层实例
const refSelectDialog: Ref<UniHelper.UniPopup | null> = ref(null)
  • ts类型有一些问题,找了好久不知道该给什么类型!!! 新手TS,有大佬的话请指出,感谢!

3.1 backgroundColor="#fff" 圆角问题 (已优化)

<uni-popup backgroundColor="#fff" />  // 可以不加了
  • 因为默认是开启适配的,需要加上背景色,否则就是透明的底部区域
  • 示例如下:
  • vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
  • 源码查看
  • vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
    vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
    vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择,vue3.0,ts,uniApp,uni-app,小程序,vue
    整理不易,如有转载请备注原文地址!

到了这里,关于vue3+ts+uniapp小程序端自定义日期选择器基于内置组件picker-view + 扩展组件 Popup 实现自定义日期选择及其他单列选择的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • uniapp 实现富文本编辑器【小程序端】

    css资源文件戳该链接:富文本css文件链接 编辑菜单我搞成吸顶效果了,方便手机编辑不用再滑到头部点编辑菜单:css实现元素吸顶效果 ————————————————————————————————————————————

    2024年02月16日
    浏览(48)
  • uniApp -- 学习笔记(vue3+ts)

    uniApp官网介绍 (一) 个人理解是官网返回一个 SelectorQuery 对象实例。 并且可以在这个实例上使用 select 等方法选择节点,并使用 boundingClientRect 等方法选择需要查询的信息。但是关于这个需要到查询信息,只有打印出来 , 在onReady 调用 let selectorQuery: UniNamespace.SelectorQuery =

    2024年02月09日
    浏览(31)
  • uniapp实现微信小程序端动态生成海报

    背景: 基于uniapp实现微信小程序中商品详情的海报生成与保存 效果图: 思路: 首先把海报上需要的内容准备好,比如用户头像,商品信息,二维码等。需要注意的是,因为二维码是动态生成的,所以需要后端传给我们,前端需要把路径和参数传给后端,后端请求微信服务接

    2024年02月12日
    浏览(35)
  • uniapp,小程序端返回上一页并传递参数

    使用场景: 从A页面跳到B页面,在数据操作后要返回A页面(使用uni.navigateBack()返回), 要求: 携带参数返回A页面,不使用链接带参数返回,不用使用缓存:uni.setStorageSync()储存数据等情况下怎么传递参数 可使用解决方案: 方法一:使用getCurrentPages() 函数获取上一页面栈的

    2024年02月08日
    浏览(36)
  • vue3 ts 定义全局变量

    在 Vue3 中使用 TypeScript 定义全局变量可以这样做: 创建一个文件,如 global.d.ts ,并在其中声明全局变量。 在 main.ts 或其他入口文件中引入该文件。 在需要使用全局变量的地方直接使用即可。 注意,这种方式只能用于定义全局变量,不能用于定义全局函数或类。

    2024年02月17日
    浏览(34)
  • uniapp条件判断app,H5,微信小程序端

    1.在页面上判断不同的端 2.JS里面判断不同的端 3.CSS里面判断不同的端

    2024年02月05日
    浏览(35)
  • 中国省市区地区选择组件(ElementPlus + Vue3 + TS )

    1.引用 2.用法 provinceAndCityData :省市数据(不带“全部”选项) regionData :省市区数据(不带“全部”选项) provinceAndCityDataPlus :省市区数据(带“全部”选项) regionDataPlus :省市区数据(带“全部”选项) CodeToText :例如:CodeToText[‘110000’]输出北京市 TextToCode :例如:

    2023年04月27日
    浏览(47)
  • uniapp 小程序 使用vue3+ts运行项目

    uniapp官网教程:uni-app官网 创建方式有2种 第一种:通过HBuilderX可视化界面创建 第二种:通过vue-cli命令行 注意:若不能直接使用命令下载,可去gitee下载模板使用 下载完模板后进行解压,利用vscode打开文件,会发现报这样的错误👇主要原因是没有下载依赖 解决以上错误:使

    2024年02月13日
    浏览(30)
  • uniapp 在app和小程序端使用webview进行数据交互

    结论:app端支持比较好可以做到实时传递,微信小程序支持比较差,小程序向url传参只能通过url,url向app传参需要特定时机(后退、组件销毁、分享、复制链接)触发才能收到消息。 以下是代码 app端(需要使用nvue) 微信小程序端(正常vue格式) 3、html端

    2024年02月16日
    浏览(33)
  • uniapp 判断微信小程序端、App端、h5端

    区分标识 写法:以 #ifdef 或 #ifndef 加 %PLATFORM% 开头,以 #endif 结尾。 #ifdef:if defined 仅在某平台存在 #ifndef:if not defined 除了某平台均存在 %PLATFORM%:平台名称 此方法支持文件有 .vue (模板里使用 ) .js (使用// 注释) .css (使用 /* 注释 */) pages.json (使用// 注释) 各预编译

    2024年02月03日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包