3
0

u-picker.vue 11 KB

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