u-picker.vue 13 KB

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