u-picker.vue 11 KB

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