cl-picker-view.uvue 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <template>
  2. <view class="cl-picker-view">
  3. <view class="cl-picker-view__header" v-if="headers.length > 0">
  4. <cl-text
  5. :pt="{
  6. className: 'flex-1 text-center'
  7. }"
  8. v-for="(label, index) in headers"
  9. :key="index"
  10. >{{ label }}</cl-text
  11. >
  12. </view>
  13. <view
  14. class="px-1"
  15. :style="{
  16. height: getUnit(height)
  17. }"
  18. >
  19. <picker-view
  20. class="h-full"
  21. :value="value"
  22. :mask-style="maskStyle"
  23. :mask-top-style="maskStyle"
  24. :mask-bottom-style="maskStyle"
  25. :immediate-change="true"
  26. :indicator-style="indicatorStyle"
  27. @change="onChange"
  28. >
  29. <picker-view-column
  30. class="cl-select-popup__column"
  31. v-for="(column, columnIndex) in columns"
  32. :key="columnIndex"
  33. >
  34. <!-- #ifdef APP-ANDROID -->
  35. <view
  36. ref="columnItemRef"
  37. :style="{
  38. height: `${itemHeight * column.length}px`
  39. }"
  40. ></view>
  41. <!-- #endif -->
  42. <!-- #ifndef APP-ANDROID -->
  43. <view
  44. class="cl-picker-view__item"
  45. :style="{
  46. height: `${itemHeight}px`
  47. }"
  48. v-for="(item, index) in column"
  49. :key="index"
  50. >
  51. <cl-text
  52. :pt="{
  53. className: parseClass([
  54. [isDark, 'text-surface-500'],
  55. [isDark && index == value[columnIndex], 'text-white']
  56. ])
  57. }"
  58. >{{ item.label }}</cl-text
  59. >
  60. </view>
  61. <!-- #endif -->
  62. </picker-view-column>
  63. </picker-view>
  64. </view>
  65. </view>
  66. </template>
  67. <script setup lang="ts">
  68. import {
  69. forInObject,
  70. getColor,
  71. isAppIOS,
  72. isDark,
  73. isEqual,
  74. isNull,
  75. parseClass,
  76. getUnit,
  77. isAppAndroid
  78. } from "@/.cool";
  79. import type { ClSelectOption } from "../../types";
  80. import { computed, nextTick, onMounted, ref, shallowRef, watch } from "vue";
  81. import type { PropType } from "vue";
  82. import { useSize } from "../../hooks";
  83. defineOptions({
  84. name: "cl-select-picker-view"
  85. });
  86. const props = defineProps({
  87. // 选择器表头
  88. headers: {
  89. type: Array as PropType<string[]>,
  90. default: () => []
  91. },
  92. // 选择器值
  93. value: {
  94. type: Array as PropType<number[]>,
  95. default: () => []
  96. },
  97. // 选择器选项
  98. columns: {
  99. type: Array as PropType<ClSelectOption[][]>,
  100. default: () => []
  101. },
  102. // 选择器选项高度
  103. itemHeight: {
  104. type: Number,
  105. default: isAppIOS() ? 50 : 42
  106. },
  107. // 选择器高度
  108. height: {
  109. type: Number,
  110. default: 300
  111. }
  112. });
  113. const emit = defineEmits(["change-value", "change-index"]);
  114. const { getScale } = useSize();
  115. // 获取窗口宽度,用于计算选择器列宽
  116. const { windowWidth } = uni.getWindowInfo();
  117. // 顶部显示表头
  118. const headers = computed(() => {
  119. return props.headers.slice(0, props.columns.length);
  120. });
  121. // 监听选择器值改变事件
  122. function onChange(e: UniPickerViewChangeEvent) {
  123. // 获取选择器当前选中值数组
  124. const indexs = e.detail.value;
  125. // 处理因快速滑动导致下级数据未及时渲染而产生的索引越界问题
  126. indexs.forEach((v, i, arr) => {
  127. if (i < props.columns.length) {
  128. const n = props.columns[i].length;
  129. if (v >= n) {
  130. arr[i] = n - 1;
  131. }
  132. }
  133. });
  134. // 相同值不触发事件
  135. if (isEqual(indexs, props.value)) {
  136. return;
  137. }
  138. // 获取所有列的值
  139. const values = props.columns.map((c, i) => {
  140. return isNull(c[indexs[i]]) ? 0 : c[indexs[i]].value;
  141. });
  142. // 返回所有列的值或下标
  143. emit("change-value", values);
  144. emit("change-index", indexs);
  145. }
  146. // 列项ref引用
  147. const columnItemRef = shallowRef<UniElement[]>([]);
  148. // 渲染列项内容
  149. const renderColumnItem = () => {
  150. // 当前全局或默认字体大小
  151. const fontSize = getScale() * 14;
  152. // 根据主题切换字体颜色(深色/浅色)
  153. const color = isDark.value ? "white" : getColor("surface-700");
  154. // 遍历所有 picker-view-column 的ref,与每列数据一一对应
  155. for (let i = 0; i < columnItemRef.value.length; i++) {
  156. const column = props.columns[i]; // 当前列的数据
  157. const dom = columnItemRef.value[i]; // 当前列对应的DOM节点
  158. // 获取节点尺寸,用于文本居中计算
  159. const rect = dom!.getBoundingClientRect();
  160. // 获取原生画布上下文
  161. const ctx = dom!.getDrawableContext()!;
  162. ctx.reset(); // 每次重绘前需先重置画布
  163. ctx.textAlign = "center";
  164. // 计算文本水平方向的中点位置
  165. const x = rect.width / 2;
  166. // 循环绘制本列的每一个选项
  167. for (let j = 0; j < column.length; j++) {
  168. ctx.fillStyle = color; // 设置文本颜色
  169. ctx.font = `${fontSize}px`;
  170. // 计算每行文本的垂直位置,使其垂直居中于item元素内
  171. const y = 12 + (props.itemHeight - fontSize) / 2 + props.itemHeight * j;
  172. ctx.fillText(column[j].label, x, y); // 绘制文本
  173. }
  174. ctx.update(); // 完成当前列绘制,刷到视图
  175. }
  176. };
  177. // 遮罩层样式
  178. const maskStyle = ref("");
  179. const renderMaskStyle = () => {
  180. if (isDark.value) {
  181. maskStyle.value = `background-image: linear-gradient(180deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0))`;
  182. }
  183. };
  184. // 计算选择器列样式
  185. const indicatorStyle = ref("");
  186. const renderIndicatorStyle = () => {
  187. // 计算选择器列样式
  188. let str = "";
  189. // 计算每列的宽
  190. const width = Math.ceil((windowWidth - 8) / props.columns.length - 10);
  191. // 选择器列样式配置
  192. const style = {
  193. height: `${props.itemHeight}px`,
  194. width: `${width}px`,
  195. left: "4px",
  196. backgroundColor: "rgba(10, 10, 10, 0.04)",
  197. borderRadius: "10px",
  198. border: "1px solid rgba(10, 10, 10, 0.2)"
  199. };
  200. // 深色模式
  201. if (isDark.value) {
  202. style.backgroundColor = "rgba(0, 0, 0, 0.01)";
  203. style.border = "1px solid rgba(255, 255, 255, 0.3)";
  204. }
  205. // ios 端样式
  206. if (isAppIOS()) {
  207. style.backgroundColor = isDark.value ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 0, 0, 0.1)";
  208. if (isDark.value) {
  209. style.border = "none";
  210. style.width = `${width - 3}px`;
  211. } else {
  212. style.width = `${width + 2}px`;
  213. }
  214. }
  215. // android 端样式
  216. if (isAppAndroid()) {
  217. style.width = `${width + 1}px`;
  218. }
  219. // 构建样式字符串
  220. forInObject(style, (value, key) => {
  221. str += `${key}: ${value};`;
  222. });
  223. indicatorStyle.value = str;
  224. };
  225. // 渲染列和样式
  226. const render = () => {
  227. renderColumnItem();
  228. renderMaskStyle();
  229. renderIndicatorStyle();
  230. };
  231. onMounted(() => {
  232. nextTick(() => {
  233. render();
  234. });
  235. watch(
  236. computed(() => [isDark.value, props.columns, props.itemHeight]),
  237. () => {
  238. render();
  239. }
  240. );
  241. });
  242. </script>
  243. <style lang="scss" scoped>
  244. .cl-picker-view {
  245. @apply w-full h-full;
  246. &__header {
  247. @apply flex flex-row items-center py-4;
  248. }
  249. &__item {
  250. @apply flex flex-row items-center justify-center;
  251. }
  252. .uni-picker-view-indicator {
  253. // #ifdef H5
  254. &::after,
  255. &::before {
  256. display: none;
  257. }
  258. // #endif
  259. }
  260. }
  261. </style>