u-picker.vue 14 KB

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