You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

416 lines
16 KiB

  1. <template>
  2. <view class="u-waterfall">
  3. <!-- 新增支持多列布局 -->
  4. <view
  5. v-for="(column, index) in columnList"
  6. :key="index"
  7. :ref="`u-column-${index}`"
  8. :id="`u-column-${index}`"
  9. class="u-column"
  10. >
  11. <slot name="column"
  12. :colIndex="index"
  13. :colList="column">
  14. </slot>
  15. <slot name="left"
  16. :colIndex="index"
  17. :leftList="column">
  18. </slot>
  19. <template v-if="!$slots['left'] && !$slots['column']" v-for="(item, itemIndex) in column" :key="itemIndex">
  20. <slot :item="item" :itemIndex="itemIndex"></slot>
  21. </template>
  22. </view>
  23. </view>
  24. </template>
  25. <script>
  26. /**
  27. * waterfall 瀴布流
  28. * @description 这是一个瀑布流形式的组件,对原组件进行升级已经支持自定义列数模式,便于适配不同屏幕。搭配loadMore 加载更多组件,让您开箱即用,眼前一亮。
  29. * @tutorial https://uview-plus.jiangruyi.com/components/waterfall.html
  30. * @property {Array} flow-list 用于渲染的数据
  31. * @property {String Number} add-time 单条数据添加到队列的时间间隔,单位ms,见上方注意事项说明(默认200)
  32. * @property {String Number} columns 瀑布流列数,默认为2,设置为auto时自动根据屏幕宽度调整列数
  33. * @example <u-waterfall :flowList="flowList"></u-waterfall>
  34. */
  35. import { mpMixin } from '../../libs/mixin/mpMixin';
  36. import { mixin } from '../../libs/mixin/mixin';
  37. import { sleep } from '../../libs/function/index';
  38. export default {
  39. name: "u-waterfall",
  40. props: {
  41. // #ifdef VUE2
  42. value: {
  43. // 瀑布流数据
  44. type: Array,
  45. required: true,
  46. default: function() {
  47. return [];
  48. }
  49. },
  50. // #endif
  51. // #ifdef VUE3
  52. modelValue: {
  53. // 瀑布流数据
  54. type: Array,
  55. required: true,
  56. default: function() {
  57. return [];
  58. }
  59. },
  60. // #endif
  61. // 每次向结构插入数据的时间间隔,单位ms
  62. // 单位ms
  63. addTime: {
  64. type: [Number, String],
  65. default: 200
  66. },
  67. // id值,用于清除某一条数据时,根据此idKey名称找到并移除,如数据为{idx: 22, name: 'lisa'}
  68. // 那么该把idKey设置为idx
  69. idKey: {
  70. type: String,
  71. default: 'id'
  72. },
  73. // 瀑布流列数
  74. columns: {
  75. type: [Number, String],
  76. default: 2
  77. },
  78. // 瀑布流最小列数
  79. columnsMin: {
  80. type: [Number, String],
  81. default: 2
  82. },
  83. // 最小列宽
  84. minColumnWidth: {
  85. type: Number,
  86. default: 230
  87. }
  88. },
  89. mixins: [mpMixin, mixin],
  90. data() {
  91. return {
  92. columnList: [[]], // 存储每列的数据
  93. children: [],
  94. // 用于标记是否已经初始化
  95. initialized: false,
  96. windowWidth: 375,
  97. windowHeight: 0
  98. }
  99. },
  100. watch: {
  101. copyFlowList: {
  102. handler(nVal, oVal) {
  103. if (!nVal || nVal.length == 0) {
  104. this.clear(false);
  105. } else {
  106. if (this.columnList.length == 1) {
  107. this.initColumnList()
  108. }
  109. // 取差值,即这一次数组变化新增的部分
  110. let startIndex = Array.isArray(oVal) && oVal.length > 0 ? oVal.length : 0;
  111. // 直接处理数据,不再使用tempList和splitData
  112. this.handleData(nVal.slice(startIndex));
  113. }
  114. },
  115. immediate: true
  116. },
  117. columns: {
  118. handler() {
  119. this.initColumnList();
  120. // 重新分配数据
  121. if (this.copyFlowList.length > 0) {
  122. this.redistributeData();
  123. }
  124. },
  125. immediate: false
  126. }
  127. },
  128. created() {
  129. this.initColumnList();
  130. },
  131. mounted() {
  132. this.initialized = true;
  133. // 添加窗口大小变化监听
  134. // #ifdef H5
  135. if (this.columns === 'auto') {
  136. uni.onWindowResize(this.handleWindowResize);
  137. }
  138. // #endif
  139. },
  140. // 添加beforeUnmount生命周期清理事件监听
  141. // #ifdef VUE3
  142. beforeUnmount() {
  143. // #ifdef H5
  144. if (this.columns === 'auto') {
  145. uni.offWindowResize(this.handleWindowResize);
  146. }
  147. // #endif
  148. },
  149. // #endif
  150. // #ifdef VUE2
  151. beforeDestroy() {
  152. // #ifdef H5
  153. if (this.columns === 'auto') {
  154. window.removeEventListener('resize', this.handleWindowResize);
  155. }
  156. // #endif
  157. },
  158. // #endif
  159. computed: {
  160. // 破坏flowList变量的引用,否则watch的结果新旧值是一样的
  161. copyFlowList() {
  162. // #ifdef VUE3
  163. if (!this.modelValue || this.modelValue.length == 0) {
  164. // console.log('clear');
  165. return [];
  166. } else {
  167. return this.cloneData(this.modelValue);
  168. }
  169. // #endif
  170. // #ifdef VUE2
  171. return this.cloneData(this.value);
  172. // #endif
  173. }
  174. },
  175. emits: ['update:modelValue', 'after-add-one', 'after-add-all'],
  176. methods: {
  177. // 初始化列数据数组
  178. initColumnList() {
  179. this.windowWidth = uni.getSystemInfoSync().windowWidth;
  180. const cols = this.getColumnsCount();
  181. // console.log(cols)
  182. this.columnList = Array.from({ length: cols }, () => []);
  183. },
  184. // 获取列数,支持auto模式
  185. getColumnsCount() {
  186. if (this.columns === 'auto') {
  187. // 列间距为10rpx(约等于7px)
  188. const columnGap = 7;
  189. // 计算可容纳的列数
  190. let columnCount = Math.max(1, Math.floor(this.windowWidth / (this.minColumnWidth + columnGap)));
  191. if (columnCount < this.columnsMin) {
  192. columnCount = this.columnsMin
  193. }
  194. return columnCount;
  195. }
  196. return parseInt(this.columns) || 2;
  197. },
  198. // 窗口大小变化处理函数
  199. handleWindowResize(res) {
  200. this.windowWidth = res.size.windowWidth
  201. this.windowHeight = res.size.windowHeight
  202. // 防抖处理,避免频繁触发
  203. if (this.resizeTimer) {
  204. clearTimeout(this.resizeTimer);
  205. }
  206. this.resizeTimer = setTimeout(() => {
  207. const newColumnsCount = this.getColumnsCount();
  208. const oldColumnsCount = this.columnList.length;
  209. // 只有列数发生变化时才重新分配数据
  210. if (newColumnsCount !== oldColumnsCount) {
  211. this.redistributeData();
  212. }
  213. }, 300);
  214. },
  215. // 重新分配所有数据
  216. async redistributeData() {
  217. // 清空所有列
  218. this.initColumnList();
  219. // 保存所有数据
  220. const allData = this.cloneData(this.copyFlowList);
  221. // 重新分配数据
  222. this.handleData(allData);
  223. },
  224. // 处理新增数据
  225. async handleData(newData) {
  226. if (!newData || newData.length === 0) return;
  227. // 初始化列高度数组
  228. const columnHeights = new Array(this.columnList.length).fill(0);
  229. // 获取各列当前高度
  230. for (let i = 0; i < this.columnList.length; i++) {
  231. try {
  232. const rect = await this.$uGetRect(`#u-column-${i}`);
  233. // console.log(`#u-column-${i}`, rect.height)
  234. columnHeights[i] = rect.height || 0;
  235. } catch (e) {
  236. columnHeights[i] = 0;
  237. }
  238. }
  239. // 分配新数据到最短的列
  240. for (let item of newData) {
  241. const minHeightIndex = this.getMinHeightColumnIndex(columnHeights);
  242. // console.log('this.columnList', this.columnList)
  243. this.columnList[minHeightIndex].push(item);
  244. // 获取实际渲染后的元素高度而不是估算
  245. await sleep(this.addTime);
  246. await this.$nextTick();
  247. try {
  248. const rect = await this.$uGetRect(`#u-column-${minHeightIndex}`);
  249. // console.log(`#u-column-${minHeightIndex}`, rect.height)
  250. if (rect.height) {
  251. columnHeights[minHeightIndex] = rect.height;
  252. // 加载一个后置事件
  253. this.$emit('after-add-one', {
  254. ...item,
  255. height: rect.height
  256. });
  257. }
  258. } catch (e) {
  259. // console.log(e)
  260. // columnHeights[i] = 0;
  261. }
  262. }
  263. // 加载所有后置事件
  264. this.$emit('after-add-all', {
  265. columnHeights: columnHeights,
  266. newData: newData
  267. });
  268. },
  269. // 获取最短列;高度相同或暂不可测时按列数据量打散,避免全部落到第一列
  270. getMinHeightColumnIndex(columnHeights) {
  271. let minIndex = 0;
  272. for (let i = 1; i < columnHeights.length; i++) {
  273. const currentHeight = Number(columnHeights[i]) || 0;
  274. const minHeight = Number(columnHeights[minIndex]) || 0;
  275. if (currentHeight < minHeight) {
  276. minIndex = i;
  277. } else if (currentHeight === minHeight) {
  278. const currentLength = this.columnList[i] ? this.columnList[i].length : 0;
  279. const minLength = this.columnList[minIndex] ? this.columnList[minIndex].length : 0;
  280. if (currentLength < minLength) {
  281. minIndex = i;
  282. }
  283. }
  284. }
  285. return minIndex;
  286. },
  287. // 复制而不是引用对象和数组
  288. cloneData(data) {
  289. return JSON.parse(JSON.stringify(data));
  290. },
  291. // 清空数据列表
  292. clear(bak = true) {
  293. this.initColumnList();
  294. // 同时清除父组件列表中的数据
  295. if (bak) {
  296. // #ifdef VUE2
  297. this.$emit('input', []);
  298. // #endif
  299. // #ifdef VUE3
  300. this.$emit('update:modelValue', []);
  301. // #endif
  302. }
  303. },
  304. // 清除某一条指定的数据,根据id实现
  305. remove(id) {
  306. // 遍历所有列查找并删除数据
  307. for (let i = 0; i < this.columnList.length; i++) {
  308. const index = this.columnList[i].findIndex(val => val[this.idKey] == id);
  309. if (index !== -1) {
  310. this.columnList[i].splice(index, 1);
  311. break;
  312. }
  313. }
  314. // 同时清除父组件的数据中的对应id的条目
  315. // #ifdef VUE2
  316. const valueIndex = this.value.findIndex(val => val[this.idKey] == id);
  317. if (valueIndex !== -1) {
  318. const newValue = this.cloneData(this.value);
  319. newValue.splice(valueIndex, 1);
  320. this.$emit('input', newValue);
  321. }
  322. // #endif
  323. // #ifdef VUE3
  324. const modelValueIndex = this.modelValue.findIndex(val => val[this.idKey] == id);
  325. if (modelValueIndex !== -1) {
  326. const newModelValue = this.cloneData(this.modelValue);
  327. newModelValue.splice(modelValueIndex, 1);
  328. this.$emit('update:modelValue', newModelValue);
  329. }
  330. // #endif
  331. },
  332. // 修改某条数据的某个属性
  333. modify(id, key, value) {
  334. let found = false;
  335. let targetItem = null;
  336. // 在所有列中查找数据
  337. for (let i = 0; i < this.columnList.length; i++) {
  338. const index = this.columnList[i].findIndex(val => val[this.idKey] == id);
  339. if (index !== -1) {
  340. // 修改对应key的值
  341. this.columnList[i][index][key] = value;
  342. targetItem = this.columnList[i][index];
  343. found = true;
  344. break;
  345. }
  346. }
  347. if (found && targetItem) {
  348. // 修改父组件的数据中的对应id的条目
  349. // #ifdef VUE2
  350. const valueIndex = this.value.findIndex(val => val[this.idKey] == id);
  351. if (valueIndex !== -1) {
  352. let data = this.cloneData(this.value);
  353. data[valueIndex][key] = value;
  354. this.$emit('input', data);
  355. }
  356. // #endif
  357. // #ifdef VUE3
  358. const modelValueIndex = this.modelValue.findIndex(val => val[this.idKey] == id);
  359. if (modelValueIndex !== -1) {
  360. let data = this.cloneData(this.modelValue);
  361. data[modelValueIndex][key] = value;
  362. this.$emit('update:modelValue', data);
  363. }
  364. // #endif
  365. }
  366. }
  367. }
  368. }
  369. </script>
  370. <style lang="scss" scoped>
  371. .u-waterfall {
  372. @include flex;
  373. flex-direction: row;
  374. align-items: flex-start;
  375. }
  376. .u-column {
  377. @include flex;
  378. flex: 1;
  379. flex-direction: column;
  380. overflow: hidden;
  381. /* #ifndef APP-NVUE */
  382. height: 100%;
  383. /* #endif */
  384. // 添加列之间的间距
  385. &:not(:first-child) {
  386. margin-left: 10rpx;
  387. }
  388. }
  389. .u-image {
  390. /* #ifndef APP-NVUE */
  391. max-width: 100%;
  392. /* #endif */
  393. }
  394. </style>