You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

336 lines
10 KiB

2 months ago
  1. <template>
  2. <view class="u-picker-warrper">
  3. <view v-if="hasInput" class="u-picker-input cursor-pointer" @click="showByClickInput = !showByClickInput">
  4. <slot>
  5. <view>
  6. {{ inputLabel && inputLabel.length ? inputLabel.join('/') : placeholder }}
  7. </view>
  8. </slot>
  9. </view>
  10. <u-popup
  11. :show="show || (hasInput && showByClickInput)"
  12. :mode="popupMode"
  13. @close="closeHandler"
  14. >
  15. <view class="u-picker">
  16. <u-toolbar
  17. v-if="showToolbar"
  18. :cancelColor="cancelColor"
  19. :confirmColor="confirmColor"
  20. :cancelText="cancelText"
  21. :confirmText="confirmText"
  22. :title="title"
  23. @cancel="cancel"
  24. @confirm="confirm"
  25. ></u-toolbar>
  26. <picker-view
  27. class="u-picker__view"
  28. :indicatorStyle="`height: ${addUnit(itemHeight)}`"
  29. :value="innerIndex"
  30. :immediateChange="immediateChange"
  31. :style="{
  32. height: `${addUnit(visibleItemCount * itemHeight)}`
  33. }"
  34. @change="changeHandler"
  35. >
  36. <picker-view-column
  37. v-for="(item, index) in innerColumns"
  38. :key="index"
  39. class="u-picker__view__column"
  40. >
  41. <view
  42. v-if="testArray(item)"
  43. class="u-picker__view__column__item u-line-1"
  44. v-for="(item1, index1) in item"
  45. :key="index1"
  46. :style="{
  47. height: addUnit(itemHeight),
  48. lineHeight: addUnit(itemHeight),
  49. fontWeight: index1 === innerIndex[index] ? 'bold' : 'normal',
  50. display: 'block'
  51. }"
  52. >{{ getItemText(item1) }}</view>
  53. </picker-view-column>
  54. </picker-view>
  55. <view
  56. v-if="loading"
  57. class="u-picker--loading"
  58. >
  59. <u-loading-icon mode="circle"></u-loading-icon>
  60. </view>
  61. </view>
  62. </u-popup>
  63. </view>
  64. </template>
  65. <script>
  66. /**
  67. * u-picker
  68. * @description 选择器
  69. * @property {Boolean} show 是否显示picker弹窗默认 false
  70. * @property {Boolean} showToolbar 是否显示顶部的操作栏默认 true
  71. * @property {String} title 顶部标题
  72. * @property {Array} columns 对象数组设置每一列的数据
  73. * @property {Boolean} loading 是否显示加载中状态默认 false
  74. * @property {String | Number} itemHeight 各列中单个选项的高度默认 44
  75. * @property {String} cancelText 取消按钮的文字默认 '取消'
  76. * @property {String} confirmText 确认按钮的文字默认 '确定'
  77. * @property {String} cancelColor 取消按钮的颜色默认 '#909193'
  78. * @property {String} confirmColor 确认按钮的颜色默认 '#3c9cff'
  79. * @property {String | Number} visibleItemCount 每列中可见选项的数量默认 5
  80. * @property {String} keyName 选项对象中需要展示的属性键名默认 'text'
  81. * @property {Boolean} closeOnClickOverlay 是否允许点击遮罩关闭选择器默认 false
  82. * @property {Array} defaultIndex 各列的默认索引
  83. * @property {Boolean} immediateChange 是否在手指松开时立即触发change事件默认 true
  84. * @event {Function} close 关闭选择器时触发
  85. * @event {Function} cancel 点击取消按钮触发
  86. * @event {Function} change 当选择值变化时触发
  87. * @event {Function} confirm 点击确定按钮返回当前选择的值
  88. */
  89. import { props } from './props';
  90. import { mpMixin } from '../../libs/mixin/mpMixin';
  91. import { mixin } from '../../libs/mixin/mixin';
  92. import { addUnit, deepClone, sleep } from '../../libs/function/index';
  93. import test from '../../libs/function/test';
  94. export default {
  95. name: 'u-picker',
  96. mixins: [mpMixin, mixin, props],
  97. data() {
  98. return {
  99. // 上一次选择的列索引
  100. lastIndex: [],
  101. // 索引值 ,对应picker-view的value
  102. innerIndex: [],
  103. // 各列的值
  104. innerColumns: [],
  105. // 上一次的变化列索引
  106. columnIndex: 0,
  107. showByClickInput: false,
  108. }
  109. },
  110. watch: {
  111. // 监听默认索引的变化,重新设置对应的值
  112. defaultIndex: {
  113. immediate: true,
  114. handler(n) {
  115. this.setIndexs(n, true)
  116. }
  117. },
  118. // 监听columns参数的变化
  119. columns: {
  120. immediate: true,
  121. deep:true,
  122. handler(n) {
  123. this.setColumns(n)
  124. }
  125. },
  126. },
  127. emits: ['close', 'cancel', 'confirm', 'change'],
  128. computed: {
  129. inputLabel() {
  130. let items = this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  131. let res = []
  132. items.forEach(element => {
  133. res.push(element[this.keyName])
  134. });
  135. return res
  136. },
  137. inputValue() {
  138. let items = this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  139. let res = []
  140. items.forEach(element => {
  141. res.push(element['id'])
  142. });
  143. return res
  144. }
  145. },
  146. methods: {
  147. addUnit,
  148. testArray: test.array,
  149. // 获取item需要显示的文字,判别为对象还是文本
  150. getItemText(item) {
  151. if (test.object(item)) {
  152. return item[this.keyName]
  153. } else {
  154. return item
  155. }
  156. },
  157. // 关闭选择器
  158. closeHandler() {
  159. if (this.closeOnClickOverlay) {
  160. if (this.hasInput) {
  161. this.showByClickInput = false
  162. }
  163. this.$emit('close')
  164. }
  165. },
  166. // 点击工具栏的取消按钮
  167. cancel() {
  168. if (this.hasInput) {
  169. this.showByClickInput = false
  170. }
  171. this.$emit('cancel')
  172. },
  173. // 点击工具栏的确定按钮
  174. confirm() {
  175. this.$emit('update:modelValue', this.inputValue)
  176. if (this.hasInput) {
  177. this.showByClickInput = false
  178. }
  179. this.$emit('confirm', {
  180. indexs: this.innerIndex,
  181. value: this.innerColumns.map((item, index) => item[this.innerIndex[index]]),
  182. values: this.innerColumns
  183. })
  184. },
  185. // 选择器某一列的数据发生变化时触发
  186. changeHandler(e) {
  187. const {
  188. value
  189. } = e.detail
  190. let index = 0,
  191. columnIndex = 0
  192. // 通过对比前后两次的列索引,得出当前变化的是哪一列
  193. for (let i = 0; i < value.length; i++) {
  194. let item = value[i]
  195. if (item !== (this.lastIndex[i] || 0)) { // 把undefined转为合法假值0
  196. // 设置columnIndex为当前变化列的索引
  197. columnIndex = i
  198. // index则为变化列中的变化项的索引
  199. index = item
  200. break // 终止循环,即使少一次循环,也是性能的提升
  201. }
  202. }
  203. this.columnIndex = columnIndex
  204. const values = this.innerColumns
  205. // 将当前的各项变化索引,设置为"上一次"的索引变化值
  206. this.setLastIndex(value)
  207. this.setIndexs(value)
  208. this.$emit('update:modelValue', this.inputValue)
  209. this.$emit('change', {
  210. // #ifndef MP-WEIXIN || MP-LARK
  211. // 微信小程序不能传递this,会因为循环引用而报错
  212. // picker: this,
  213. // #endif
  214. value: this.innerColumns.map((item, index) => item[value[index]]),
  215. index,
  216. indexs: value,
  217. // values为当前变化列的数组内容
  218. values,
  219. columnIndex
  220. })
  221. },
  222. // 设置index索引,此方法可被外部调用设置
  223. setIndexs(index, setLastIndex) {
  224. this.innerIndex = deepClone(index)
  225. if (setLastIndex) {
  226. this.setLastIndex(index)
  227. }
  228. },
  229. // 记录上一次的各列索引位置
  230. setLastIndex(index) {
  231. // 当能进入此方法,意味着当前设置的各列默认索引,即为“上一次”的选中值,需要记录,是因为changeHandler中
  232. // 需要拿前后的变化值进行对比,得出当前发生改变的是哪一列
  233. this.lastIndex = deepClone(index)
  234. },
  235. // 设置对应列选项的所有值
  236. setColumnValues(columnIndex, values) {
  237. // 替换innerColumns数组中columnIndex索引的值为values,使用的是数组的splice方法
  238. this.innerColumns.splice(columnIndex, 1, values)
  239. // 替换完成之后将修改列之后的已选值置空
  240. this.setLastIndex(this.innerIndex.slice(0, columnIndex))
  241. // 拷贝一份原有的innerIndex做临时变量,将大于当前变化列的所有的列的默认索引设置为0
  242. let tmpIndex = deepClone(this.innerIndex)
  243. for (let i = 0; i < this.innerColumns.length; i++) {
  244. if (i > this.columnIndex) {
  245. tmpIndex[i] = 0
  246. }
  247. }
  248. // 一次性赋值,不能单个修改,否则无效
  249. this.setIndexs(tmpIndex)
  250. },
  251. // 获取对应列的所有选项
  252. getColumnValues(columnIndex) {
  253. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  254. // 索引如果在外部change的回调中调用getColumnValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  255. (async () => {
  256. await sleep()
  257. })()
  258. return this.innerColumns[columnIndex]
  259. },
  260. // 设置整体各列的columns的值
  261. setColumns(columns) {
  262. // console.log(columns)
  263. this.innerColumns = deepClone(columns)
  264. // 如果在设置各列数据时,没有被设置默认的各列索引defaultIndex,那么用0去填充它,数组长度为列的数量
  265. if (this.innerIndex.length === 0) {
  266. this.innerIndex = new Array(columns.length).fill(0)
  267. }
  268. },
  269. // 获取各列选中值对应的索引
  270. getIndexs() {
  271. return this.innerIndex
  272. },
  273. // 获取各列选中的值
  274. getValues() {
  275. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  276. // 索引如果在外部change的回调中调用getValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  277. (async () => {
  278. await sleep()
  279. })()
  280. return this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  281. }
  282. },
  283. }
  284. </script>
  285. <style lang="scss" scoped>
  286. @import "../../libs/css/components.scss";
  287. .u-picker {
  288. position: relative;
  289. &__view {
  290. &__column {
  291. @include flex;
  292. flex: 1;
  293. justify-content: center;
  294. &__item {
  295. @include flex;
  296. justify-content: center;
  297. align-items: center;
  298. font-size: 16px;
  299. text-align: center;
  300. /* #ifndef APP-NVUE */
  301. display: block;
  302. /* #endif */
  303. color: $u-main-color;
  304. &--disabled {
  305. /* #ifndef APP-NVUE */
  306. cursor: not-allowed;
  307. /* #endif */
  308. opacity: 0.35;
  309. }
  310. }
  311. }
  312. }
  313. &--loading {
  314. position: absolute;
  315. top: 0;
  316. right: 0;
  317. left: 0;
  318. bottom: 0;
  319. @include flex;
  320. justify-content: center;
  321. align-items: center;
  322. background-color: rgba(255, 255, 255, 0.87);
  323. z-index: 1000;
  324. }
  325. }
  326. </style>