u-picker.vue 15 KB

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