u-picker.vue 14 KB

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