u-picker.vue 15 KB

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