u-picker.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. <view class="input-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 (currentCols && Object.prototype.toString.call(currentCols) === '[object Object]') {
  169. currentCols.forEach((item, index2) => {
  170. if (item[this.keyName] == element) {
  171. arr.push(index2)
  172. }
  173. })
  174. } else {
  175. currentCols.forEach((item, index2) => {
  176. if (item == element) {
  177. arr.push(index2)
  178. }
  179. })
  180. }
  181. });
  182. // alert(arr)
  183. if (arr.length == 0 && this.defaultIndex) {
  184. } else {
  185. this.setIndexs(arr, true)
  186. }
  187. }
  188. }
  189. }
  190. }
  191. },
  192. emits: ['close', 'cancel', 'confirm', 'change', 'update:modelValue', 'update:show'],
  193. computed: {
  194. // input的props
  195. inputPropsInner() {
  196. return {
  197. border: this.inputBorder,
  198. placeholder: this.placeholder,
  199. disabled: this.disabled,
  200. disabledColor: this.disabledColor,
  201. ...this.inputProps
  202. }
  203. },
  204. //已选&&已确认的值显示在input上面的文案
  205. inputLabel() {
  206. let firstItem = this.innerColumns[0] && this.innerColumns[0][0];
  207. // //区分是不是对象数组
  208. if (firstItem && Object.prototype.toString.call(firstItem) === '[object Object]') {
  209. let res = this.innerColumns[0].filter(item => this.modelValue.includes(item['id']))
  210. res = res.map(item => item[this.keyName]);
  211. return res.join("/");
  212. } else {
  213. //用户确定的值,才显示到输入框
  214. return this.modelValue.join("/");
  215. }
  216. },
  217. //已选,待确认的值
  218. inputValue() {
  219. let items = this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  220. let res = []
  221. //区分是不是对象数组
  222. if (items[0] && Object.prototype.toString.call(items[0]) === '[object Object]') {
  223. //对象数组返回属性值集合
  224. items.forEach(element => {
  225. res.push(element && element[this.valueName])
  226. });
  227. } else {
  228. //非对象数组返回元素集合
  229. items.forEach((element, index) => {
  230. res.push(element)
  231. });
  232. }
  233. return res
  234. }
  235. },
  236. methods: {
  237. addUnit,
  238. testArray: test.array,
  239. onShowByClickInput(){
  240. if(!this.disabled){
  241. this.showByClickInput=!this.showByClickInput;
  242. }
  243. },
  244. // 获取item需要显示的文字,判别为对象还是文本
  245. getItemText(item) {
  246. if (test.object(item)) {
  247. return item[this.keyName]
  248. } else {
  249. return item
  250. }
  251. },
  252. // 关闭选择器
  253. closeHandler() {
  254. if (this.closeOnClickOverlay) {
  255. if (this.hasInput) {
  256. this.showByClickInput = false
  257. }
  258. this.setDefault()
  259. this.$emit('update:show', false)
  260. this.$emit('close')
  261. }
  262. },
  263. // 点击工具栏的取消按钮
  264. cancel() {
  265. if (this.hasInput) {
  266. this.showByClickInput = false
  267. }
  268. this.setDefault()
  269. this.$emit('update:show', false)
  270. this.$emit('cancel')
  271. },
  272. setDefault() {
  273. let arr = [0]
  274. if (this.lastIndex.length == 0) {
  275. //如果有默认值&&默认值的数组长度是正确的,就用默认值
  276. if (Array.isArray(this.defaultIndex) && this.defaultIndex.length == this.innerColumns.length) {
  277. arr = [...this.defaultIndex];
  278. } else {
  279. //否则默认都选中第一个
  280. arr = Array(this.innerColumns.length).fill(0);
  281. }
  282. } else {
  283. arr = deepClone(this.lastIndex)
  284. }
  285. this.setLastIndex(arr)
  286. this.setIndexs(arr)
  287. },
  288. // 点击工具栏的确定按钮
  289. confirm() {
  290. // 如果用户有没有触发过change
  291. if (!this.currentActiveValue.length) {
  292. this.setDefault()
  293. }
  294. this.$emit('update:modelValue', this.inputValue)
  295. if (this.hasInput) {
  296. this.showByClickInput = false
  297. }
  298. this.setLastIndex(this.innerIndex)
  299. this.$emit('update:show', false)
  300. this.$emit('confirm', {
  301. indexs: this.innerIndex,
  302. value: this.innerColumns.map((item, index) => item[this.innerIndex[index]]),
  303. values: this.innerColumns
  304. })
  305. },
  306. // 选择器某一列的数据发生变化时触发
  307. changeHandler(e) {
  308. const {
  309. value
  310. } = e.detail
  311. let index = 0,
  312. columnIndex = 0
  313. //记录用户选中但是还没确认的值
  314. this.currentActiveValue = value;
  315. // 通过对比前后两次的列索引,得出当前变化的是哪一列
  316. for (let i = 0; i < value.length; i++) {
  317. let item = value[i]
  318. if (item !== (this.lastIndex[i] || 0)) { // 把undefined转为合法假值0
  319. // 设置columnIndex为当前变化列的索引
  320. columnIndex = i
  321. // index则为变化列中的变化项的索引
  322. index = item
  323. break // 终止循环,即使少一次循环,也是性能的提升
  324. }
  325. }
  326. this.columnIndex = columnIndex
  327. const values = this.innerColumns
  328. // 将当前的各项变化索引,设置为"上一次"的索引变化值
  329. // this.setLastIndex(value)
  330. this.setIndexs(value)
  331. //如果是非自带输入框才会在change时候触发v-model绑值的变化
  332. //否则会非常的奇怪,用户未确认,值就变了
  333. // if (!this.hasInput) {
  334. // this.$emit('update:modelValue', this.inputValue)
  335. // }
  336. this.$emit('change', {
  337. // #ifndef MP-WEIXIN || MP-LARK
  338. // 微信小程序不能传递this,会因为循环引用而报错
  339. // picker: this,
  340. // #endif
  341. value: this.innerColumns.map((item, index) => item[value[index]]),
  342. index,
  343. indexs: value,
  344. // values为当前变化列的数组内容
  345. values,
  346. columnIndex
  347. })
  348. },
  349. // 设置index索引,此方法可被外部调用设置
  350. setIndexs(index, setLastIndex) {
  351. this.innerIndex = deepClone(index)
  352. if (setLastIndex) {
  353. this.setLastIndex(index)
  354. }
  355. },
  356. // 记录上一次的各列索引位置
  357. setLastIndex(index) {
  358. // 当能进入此方法,意味着当前设置的各列默认索引,即为“上一次”的选中值,需要记录,是因为changeHandler中
  359. // 需要拿前后的变化值进行对比,得出当前发生改变的是哪一列
  360. this.lastIndex = deepClone(index)
  361. },
  362. // 设置对应列选项的所有值
  363. setColumnValues(columnIndex, values) {
  364. // 替换innerColumns数组中columnIndex索引的值为values,使用的是数组的splice方法
  365. this.innerColumns.splice(columnIndex, 1, values)
  366. // 替换完成之后将修改列之后的已选值置空
  367. this.setLastIndex(this.innerIndex.slice(0, columnIndex))
  368. // 拷贝一份原有的innerIndex做临时变量,将大于当前变化列的所有的列的默认索引设置为0
  369. let tmpIndex = deepClone(this.innerIndex)
  370. for (let i = 0; i < this.innerColumns.length; i++) {
  371. if (i > this.columnIndex) {
  372. tmpIndex[i] = 0
  373. }
  374. }
  375. // 一次性赋值,不能单个修改,否则无效
  376. this.setIndexs(tmpIndex)
  377. },
  378. // 获取对应列的所有选项
  379. getColumnValues(columnIndex) {
  380. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  381. // 索引如果在外部change的回调中调用getColumnValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  382. (async () => {
  383. await sleep()
  384. })()
  385. return this.innerColumns[columnIndex]
  386. },
  387. // 设置整体各列的columns的值
  388. setColumns(columns) {
  389. // console.log(columns)
  390. this.innerColumns = deepClone(columns)
  391. // 如果在设置各列数据时,没有被设置默认的各列索引defaultIndex,那么用0去填充它,数组长度为列的数量
  392. if (this.innerIndex.length === 0) {
  393. this.innerIndex = new Array(columns.length).fill(0)
  394. }
  395. },
  396. // 获取各列选中值对应的索引
  397. getIndexs() {
  398. return this.innerIndex
  399. },
  400. // 获取各列选中的值
  401. getValues() {
  402. // 进行同步阻塞,因为外部得到change事件之后,可能需要执行setColumnValues更新列的值
  403. // 索引如果在外部change的回调中调用getValues的话,可能无法得到变更后的列值,这里进行一定延时,保证值的准确性
  404. (async () => {
  405. await sleep()
  406. })()
  407. return this.innerColumns.map((item, index) => item[this.innerIndex[index]])
  408. }
  409. },
  410. }
  411. </script>
  412. <style lang="scss" scoped>
  413. .u-picker {
  414. position: relative;
  415. &-input {
  416. position: relative;
  417. .input-cover {
  418. opacity: 0;
  419. position: absolute;
  420. top: 0;
  421. bottom: 0;
  422. left: 0;
  423. right: 0;
  424. z-index:1;
  425. }
  426. }
  427. &__view {
  428. &__column {
  429. @include flex;
  430. flex: 1;
  431. justify-content: center;
  432. &__item {
  433. @include flex;
  434. justify-content: center;
  435. align-items: center;
  436. font-size: 16px;
  437. text-align: center;
  438. /* #ifndef APP-NVUE */
  439. display: block;
  440. /* #endif */
  441. color: $u-main-color;
  442. &--disabled {
  443. /* #ifndef APP-NVUE */
  444. cursor: not-allowed;
  445. /* #endif */
  446. opacity: 0.35;
  447. }
  448. }
  449. }
  450. }
  451. &--loading {
  452. position: absolute;
  453. top: 0;
  454. right: 0;
  455. left: 0;
  456. bottom: 0;
  457. @include flex;
  458. justify-content: center;
  459. align-items: center;
  460. background-color: rgba(255, 255, 255, 0.87);
  461. z-index: 1000;
  462. }
  463. }
  464. </style>