Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

506 строки
16 KiB

  1. <template>
  2. <view class="u-picker-wraper">
  3. <view v-if="hasInput" class="u-picker-input cursor-pointer" @click="onShowByClickInput">
  4. <slot :value="inputLabel">
  5. </slot>
  6. <slot name="trigger" :value="inputLabel">
  7. </slot>
  8. <up-input
  9. v-if="!$slots['default'] && !$slots['$default'] && !$slots['trigger']"
  10. :readonly="true"
  11. v-model="inputLabel"
  12. v-bind="inputPropsInner">
  13. </up-input>
  14. <cover-view class="input-cover"></cover-view>
  15. </view>
  16. <u-popup
  17. :show="show || (hasInput && showByClickInput)"
  18. :mode="popupMode"
  19. :zIndex="zIndex"
  20. :bgColor="bgColor"
  21. :round="round"
  22. :duration="duration"
  23. :pageInline="pageInline"
  24. :overlayOpacity="overlayOpacity"
  25. @close="closeHandler"
  26. >
  27. <view class="u-picker">
  28. <u-toolbar
  29. v-if="showToolbar"
  30. :cancelColor="cancelColor"
  31. :confirmColor="confirmColor"
  32. :cancelText="cancelText"
  33. :confirmText="confirmText"
  34. :title="title"
  35. :rightSlot="toolbarRightSlot ? true : false"
  36. @cancel="cancel"
  37. @confirm="confirm"
  38. >
  39. <template #right>
  40. <slot name="toolbar-right"></slot>
  41. </template>
  42. </u-toolbar>
  43. <slot name="toolbar-bottom"></slot>
  44. <picker-view
  45. class="u-picker__view"
  46. :mask-class="maskClass"
  47. :mask-style="maskStyleInner"
  48. :indicatorStyle="`height: ${addUnit(itemHeight, 'px')}`"
  49. :value="innerIndex"
  50. :immediateChange="immediateChange"
  51. :style="{
  52. height: `${addUnit(visibleItemCount * itemHeight, 'px')}`
  53. }"
  54. @change="changeHandler"
  55. >
  56. <picker-view-column
  57. v-for="(item, index) in innerColumns"
  58. :key="index"
  59. class="u-picker__view__column"
  60. >
  61. <view
  62. v-if="testArray(item)"
  63. class="u-picker__view__column__item u-line-1"
  64. :class="[index1 === innerIndex[index] && 'u-picker__view__column__item--selected']"
  65. v-for="(item1, index1) in item"
  66. :key="index1"
  67. :style="{
  68. height: addUnit(itemHeight, 'px'),
  69. lineHeight: addUnit(itemHeight, 'px'),
  70. fontWeight: index1 === innerIndex[index] ? 'bold' : 'normal',
  71. display: 'block'
  72. }"
  73. >{{ getItemText(item1) }}</view>
  74. </picker-view-column>
  75. </picker-view>
  76. <view
  77. v-if="loading"
  78. class="u-picker--loading"
  79. >
  80. <u-loading-icon mode="circle"></u-loading-icon>
  81. </view>
  82. </view>
  83. </u-popup>
  84. </view>
  85. </template>
  86. <script>
  87. /**
  88. * u-picker
  89. * @description 选择器
  90. * @property {Boolean} show 是否显示picker弹窗(默认 false )
  91. * @property {Boolean} showToolbar 是否显示顶部的操作栏(默认 true )
  92. * @property {String} title 顶部标题
  93. * @property {Array} columns 对象数组,设置每一列的数据
  94. * @property {Boolean} loading 是否显示加载中状态(默认 false )
  95. * @property {String | Number} itemHeight 各列中,单个选项的高度(默认 44 )
  96. * @property {String} cancelText 取消按钮的文字(默认 '取消' )
  97. * @property {String} confirmText 确认按钮的文字(默认 '确定' )
  98. * @property {String} cancelColor 取消按钮的颜色(默认 '#909193' )
  99. * @property {String} confirmColor 确认按钮的颜色(默认 '#3c9cff' )
  100. * @property {String | Number} visibleItemCount 每列中可见选项的数量(默认 5 )
  101. * @property {String} keyName 选项对象中,需要展示的属性键名(默认 'text' )
  102. * @property {Boolean} closeOnClickOverlay 是否允许点击遮罩关闭选择器(默认 false )
  103. * @property {Array} defaultIndex 各列的默认索引
  104. * @property {Boolean} immediateChange 是否在手指松开时立即触发change事件(默认 true )
  105. * @property {String | Number} round 圆角值(默认 0)
  106. * @property {String } bgColor 背景色值(默认 '' )
  107. * @property {String | Number} duration 动画时长,单位ms (默认 300 )
  108. * @property {String | Number} overlayDuration 遮罩层动画时长,单位ms (默认 350 )
  109. * @event {Function} close 关闭选择器时触发
  110. * @event {Function} cancel 点击取消按钮触发
  111. * @event {Function} change 当选择值变化时触发
  112. * @event {Function} confirm 点击确定按钮,返回当前选择的值
  113. */
  114. import { props } from './props';
  115. import { mpMixin } from '../../libs/mixin/mpMixin';
  116. import { mixin } from '../../libs/mixin/mixin';
  117. import { addUnit, deepClone, sleep } from '../../libs/function/index';
  118. import test from '../../libs/function/test';
  119. export default {
  120. name: 'u-picker',
  121. mixins: [mpMixin, mixin, props],
  122. data() {
  123. return {
  124. // 上一次选择的列索引
  125. lastIndex: [],
  126. // 索引值 ,对应picker-view的value
  127. innerIndex: [],
  128. // 各列的值
  129. innerColumns: [],
  130. // 上一次的变化列索引
  131. columnIndex: 0,
  132. showByClickInput: false,
  133. currentActiveValue: [] //当前用户选中,但是还没确认的值,用户没做change操作时候,点击确认可以默认选中第一个
  134. }
  135. },
  136. watch: {
  137. // 监听columns参数的变化
  138. columns: {
  139. immediate: true,
  140. deep:true,
  141. handler(n) {
  142. this.setColumns(n)
  143. }
  144. },
  145. // 监听默认索引的变化,重新设置对应的值
  146. defaultIndex: {
  147. immediate: true,
  148. deep:true,
  149. handler(n,o) {
  150. // 修复uniapp调用子组件直接:defaultIndex="[0]"这样写
  151. // v-model的值变化时候导致defaultIndexwatch也会执行的问题
  152. //单纯vue不会出现
  153. if (!o || n.join("/") != o.join("/")) {
  154. this.setIndexs(n, true)
  155. }
  156. }
  157. },
  158. modelValue: {
  159. immediate: true,
  160. deep:true,
  161. handler(n,o) {
  162. // 修复uniapp调用子组件直接:defaultIndex="[0]"这样写
  163. // v-model的值变化时候导致defaultIndexwatch也会执行的问题
  164. //单纯vue不会出现
  165. if (!o || n.join("/") != o.join("/")) {
  166. let arr = [];
  167. if (n != null) {
  168. n.forEach((element, index) => {
  169. let currentCols = this.getColumnValues(index)
  170. if(!Array.isArray(currentCols) && currentCols.length===0) {
  171. return
  172. }
  173. if (typeof currentCols[0] === 'object') {
  174. currentCols.forEach((item, index2) => {
  175. if (item[this.valueName] == element) {
  176. arr.push(index2)
  177. }
  178. })
  179. } else {
  180. currentCols.forEach((item, index2) => {
  181. if (item == element) {
  182. arr.push(index2)
  183. }
  184. })
  185. }
  186. });
  187. // alert(arr)
  188. if (arr.length == 0 && this.defaultIndex) {
  189. } else {
  190. this.setIndexs(arr, true)
  191. }
  192. }
  193. }
  194. }
  195. }
  196. },
  197. emits: ['close', 'cancel', 'confirm', 'change', 'update:modelValue', 'update:show'],
  198. computed: {
  199. // input的props
  200. inputPropsInner() {
  201. return {
  202. border: this.inputBorder,
  203. placeholder: this.placeholder,
  204. disabled: this.disabled,
  205. disabledColor: this.disabledColor,
  206. ...this.inputProps
  207. }
  208. },
  209. //已选&&已确认的值显示在input上面的文案
  210. inputLabel() {
  211. let firstItem = this.innerColumns[0] && this.innerColumns[0][0];
  212. // //区分是不是对象数组
  213. if (firstItem && Object.prototype.toString.call(firstItem) === '[object Object]') {
  214. let res = this.innerColumns[0].filter(item => this.modelValue.includes(item[this.valueName]))
  215. res = res.map(item => item[this.keyName]);
  216. return res.join("/");
  217. } else {
  218. //用户确定的值,才显示到输入框
  219. return this.modelValue.join("/");
  220. }
  221. },
  222. //已选,待确认的值
  223. inputValue() {
  224. let items = this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  225. let res = []
  226. //区分是不是对象数组
  227. if (items[0] && Object.prototype.toString.call(items[0]) === '[object Object]') {
  228. //对象数组返回属性值集合
  229. items.forEach(element => {
  230. res.push(element && element[this.valueName])
  231. });
  232. } else {
  233. //非对象数组返回元素集合
  234. items.forEach((element, index) => {
  235. res.push(element)
  236. });
  237. }
  238. return res
  239. },
  240. maskStyleInner() {
  241. // 显式传入时,始终以外部传参为准(即使传空字符串)
  242. if (this.upHasProp('maskStyle')) {
  243. return this.maskStyle || ''
  244. }
  245. if (this.upThemeIsDark) {
  246. const topBottomStrong = 'rgba(28, 28, 30, 0.95)'
  247. const topBottomWeak = 'rgba(28, 28, 30, 0.6)'
  248. return `background-image: linear-gradient(180deg, ${topBottomStrong}, ${topBottomWeak}), linear-gradient(0deg, ${topBottomStrong}, ${topBottomWeak});`
  249. }
  250. return ''
  251. }
  252. },
  253. methods: {
  254. addUnit,
  255. testArray: test.array,
  256. onShowByClickInput(){
  257. if(!this.disabled){
  258. this.showByClickInput=!this.showByClickInput;
  259. }
  260. },
  261. // 获取item需要显示的文字,判别为对象还是文本
  262. getItemText(item) {
  263. if (test.object(item)) {
  264. return item[this.keyName]
  265. } else {
  266. return item
  267. }
  268. },
  269. // 关闭选择器
  270. closeHandler() {
  271. if (this.closeOnClickOverlay) {
  272. if (this.hasInput) {
  273. this.showByClickInput = false
  274. }
  275. this.setDefault()
  276. this.$emit('update:show', false)
  277. this.$emit('close')
  278. }
  279. },
  280. // 点击工具栏的取消按钮
  281. cancel() {
  282. if (this.hasInput) {
  283. this.showByClickInput = false
  284. }
  285. this.setDefault()
  286. this.$emit('update:show', false)
  287. this.$emit('cancel')
  288. },
  289. setDefault() {
  290. let arr = [0]
  291. if (this.lastIndex.length == 0) {
  292. //如果有默认值&&默认值的数组长度是正确的,就用默认值
  293. if (Array.isArray(this.defaultIndex) && this.defaultIndex.length == this.innerColumns.length) {
  294. arr = [...this.defaultIndex];
  295. } else {
  296. //否则默认都选中第一个
  297. arr = Array(this.innerColumns.length).fill(0);
  298. }
  299. } else {
  300. arr = deepClone(this.lastIndex)
  301. }
  302. this.setLastIndex(arr)
  303. this.setIndexs(arr)
  304. },
  305. // 点击工具栏的确定按钮
  306. confirm() {
  307. // 如果用户有没有触发过change
  308. if (!this.currentActiveValue.length) {
  309. this.setDefault()
  310. }
  311. this.$emit('update:modelValue', this.inputValue)
  312. if (this.hasInput) {
  313. this.showByClickInput = false
  314. }
  315. this.setLastIndex(this.innerIndex)
  316. this.$emit('update:show', false)
  317. this.$emit('confirm', {
  318. indexs: this.innerIndex,
  319. value: this.innerColumns.map((item, index) => item[this.innerIndex[index]]),
  320. values: this.innerColumns
  321. })
  322. },
  323. // 选择器某一列的数据发生变化时触发
  324. changeHandler(e) {
  325. const {
  326. value
  327. } = e.detail
  328. let index = 0,
  329. columnIndex = 0
  330. //记录用户选中但是还没确认的值
  331. this.currentActiveValue = value;
  332. // 通过对比前后两次的列索引,得出当前变化的是哪一列
  333. for (let i = 0; i < value.length; i++) {
  334. let item = value[i]
  335. if (item !== undefined && item !== (this.lastIndex[i] || 0)) { // 把undefined转为合法假值0
  336. // 设置columnIndex为当前变化列的索引
  337. columnIndex = i
  338. // index则为变化列中的变化项的索引
  339. index = item
  340. break // 终止循环,即使少一次循环,也是性能的提升
  341. }
  342. }
  343. this.columnIndex = columnIndex
  344. const values = this.innerColumns
  345. // 将当前的各项变化索引,设置为"上一次"的索引变化值
  346. // this.setLastIndex(value)
  347. this.setIndexs(value)
  348. //如果是非自带输入框才会在change时候触发v-model绑值的变化
  349. //否则会非常的奇怪,用户未确认,值就变了
  350. // if (!this.hasInput) {
  351. // this.$emit('update:modelValue', this.inputValue)
  352. // }
  353. this.$emit('change', {
  354. // #ifndef MP-WEIXIN || MP-LARK
  355. // 微信小程序不能传递this,会因为循环引用而报错
  356. // picker: this,
  357. // #endif
  358. value: this.innerColumns.map((item, index) => item[value[index]]),
  359. index,
  360. indexs: value,
  361. // values为当前变化列的数组内容
  362. values,
  363. columnIndex
  364. })
  365. },
  366. // 设置index索引,此方法可被外部调用设置
  367. setIndexs(index, setLastIndex) {
  368. this.innerIndex = deepClone(index)
  369. if (setLastIndex) {
  370. this.setLastIndex(index)
  371. }
  372. },
  373. // 记录上一次的各列索引位置
  374. setLastIndex(index) {
  375. // 当能进入此方法,意味着当前设置的各列默认索引,即为“上一次”的选中值,需要记录,是因为changeHandler中
  376. // 需要拿前后的变化值进行对比,得出当前发生改变的是哪一列
  377. this.lastIndex = deepClone(index)
  378. },
  379. // 设置对应列选项的所有值
  380. setColumnValues(columnIndex, values) {
  381. // 替换innerColumns数组中columnIndex索引的值为values,使用的是数组的splice方法
  382. this.innerColumns.splice(columnIndex, 1, values)
  383. // 替换完成之后将修改列之后的已选值置空
  384. this.setLastIndex(this.innerIndex.slice(0, columnIndex))
  385. // 拷贝一份原有的innerIndex做临时变量,将大于当前变化列的所有的列的默认索引设置为0
  386. let tmpIndex = deepClone(this.innerIndex)
  387. for (let i = 0; i < this.innerColumns.length; i++) {
  388. if (i > this.columnIndex) {
  389. tmpIndex[i] = 0
  390. }
  391. }
  392. // 一次性赋值,不能单个修改,否则无效
  393. this.setIndexs(tmpIndex)
  394. },
  395. // 获取对应列的所有选项
  396. getColumnValues(columnIndex) {
  397. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  398. // 索引如果在外部change的回调中调用getColumnValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  399. (async () => {
  400. await sleep()
  401. })()
  402. return this.innerColumns[columnIndex]
  403. },
  404. // 设置整体各列的columns的值
  405. setColumns(columns) {
  406. // console.log(columns)
  407. const prevColumns = this.innerColumns
  408. this.innerColumns = deepClone(columns)
  409. // 如果在设置各列数据时,没有被设置默认的各列索引defaultIndex,那么用0去填充它,数组长度为列的数量
  410. if (this.innerIndex.length === 0) {
  411. this.innerIndex = new Array(columns.length).fill(0)
  412. } else {
  413. // 修复异步columns加载时defaultIndex位置不更新的问题 (issue #841)
  414. // 当某列从空数组变为有数据时,picker-view不会因为:value未变化而重新滚动到指定位置
  415. // 需要通过先清空再赋值的方式强制触发picker-view的滚动更新
  416. const hasColumnsChangedFromEmpty = columns.some(
  417. (col, i) => col && col.length > 0 && (!prevColumns[i] || prevColumns[i].length === 0)
  418. )
  419. if (hasColumnsChangedFromEmpty) {
  420. const targetIndex = deepClone(this.innerIndex)
  421. this.innerIndex = []
  422. this.$nextTick(() => {
  423. this.innerIndex = targetIndex
  424. })
  425. }
  426. }
  427. },
  428. // 获取各列选中值对应的索引
  429. getIndexs() {
  430. return this.innerIndex
  431. },
  432. // 获取各列选中的值
  433. getValues() {
  434. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  435. // 索引如果在外部change的回调中调用getValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  436. (async () => {
  437. await sleep()
  438. })()
  439. return this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  440. }
  441. },
  442. }
  443. </script>
  444. <style lang="scss" scoped>
  445. .u-picker {
  446. position: relative;
  447. &-input {
  448. position: relative;
  449. .input-cover {
  450. opacity: 0;
  451. position: absolute;
  452. top: 0;
  453. bottom: 0;
  454. left: 0;
  455. right: 0;
  456. z-index:1;
  457. }
  458. }
  459. &__view {
  460. &__column {
  461. @include flex;
  462. flex: 1;
  463. justify-content: center;
  464. &__item {
  465. @include flex;
  466. justify-content: center;
  467. align-items: center;
  468. font-size: 16px;
  469. text-align: center;
  470. /* #ifndef APP-NVUE */
  471. display: block;
  472. /* #endif */
  473. color: $u-main-color;
  474. &--disabled {
  475. /* #ifndef APP-NVUE */
  476. cursor: not-allowed;
  477. /* #endif */
  478. opacity: 0.35;
  479. }
  480. }
  481. }
  482. }
  483. &--loading {
  484. position: absolute;
  485. top: 0;
  486. right: 0;
  487. left: 0;
  488. bottom: 0;
  489. @include flex;
  490. justify-content: center;
  491. align-items: center;
  492. background-color: var(--up-card-bg-color, #ffffff);
  493. z-index: 1000;
  494. }
  495. }
  496. </style>