u-waterfall.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 = columnHeights.indexOf(Math.min(...columnHeights));
  242. // console.log('this.columnList', this.columnList)
  243. this.columnList[minHeightIndex].push(item);
  244. // 获取实际渲染后的元素高度而不是估算
  245. await sleep(this.addTime)
  246. await this.$nextTick(async () => {
  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. // this.$nextTick(async () => {
  264. // try {
  265. // // 等待DOM更新后获取实际高度
  266. // const lastIndex = this.columnList[minHeightIndex].length - 1;
  267. // const el = this.$refs[`u-column-${minHeightIndex}`][0].children[lastIndex];
  268. // if (el) {
  269. // const rect = await this.$uGetRect(el);
  270. // const actualHeight = rect.height || 100;
  271. // columnHeights[minHeightIndex] += actualHeight;
  272. // } else {
  273. // // 备用方案:如果无法获取实际高度,则使用默认值
  274. // columnHeights[minHeightIndex] += 100;
  275. // }
  276. // } catch (e) {
  277. // // 出错时使用默认高度
  278. // console.log(e)
  279. // columnHeights[minHeightIndex] += 100;
  280. // }
  281. // });
  282. }
  283. // 加载所有后置事件
  284. this.$emit('after-add-all', {
  285. columnHeights: columnHeights,
  286. newData: newData
  287. });
  288. },
  289. // 复制而不是引用对象和数组
  290. cloneData(data) {
  291. return JSON.parse(JSON.stringify(data));
  292. },
  293. // 清空数据列表
  294. clear(bak = true) {
  295. this.initColumnList();
  296. // 同时清除父组件列表中的数据
  297. if (bak) {
  298. // #ifdef VUE2
  299. this.$emit('input', []);
  300. // #endif
  301. // #ifdef VUE3
  302. this.$emit('update:modelValue', []);
  303. // #endif
  304. }
  305. },
  306. // 清除某一条指定的数据,根据id实现
  307. remove(id) {
  308. // 遍历所有列查找并删除数据
  309. for (let i = 0; i < this.columnList.length; i++) {
  310. const index = this.columnList[i].findIndex(val => val[this.idKey] == id);
  311. if (index !== -1) {
  312. this.columnList[i].splice(index, 1);
  313. break;
  314. }
  315. }
  316. // 同时清除父组件的数据中的对应id的条目
  317. // #ifdef VUE2
  318. const valueIndex = this.value.findIndex(val => val[this.idKey] == id);
  319. if (valueIndex !== -1) {
  320. const newValue = this.cloneData(this.value);
  321. newValue.splice(valueIndex, 1);
  322. this.$emit('input', newValue);
  323. }
  324. // #endif
  325. // #ifdef VUE3
  326. const modelValueIndex = this.modelValue.findIndex(val => val[this.idKey] == id);
  327. if (modelValueIndex !== -1) {
  328. const newModelValue = this.cloneData(this.modelValue);
  329. newModelValue.splice(modelValueIndex, 1);
  330. this.$emit('update:modelValue', newModelValue);
  331. }
  332. // #endif
  333. },
  334. // 修改某条数据的某个属性
  335. modify(id, key, value) {
  336. let found = false;
  337. let targetItem = null;
  338. // 在所有列中查找数据
  339. for (let i = 0; i < this.columnList.length; i++) {
  340. const index = this.columnList[i].findIndex(val => val[this.idKey] == id);
  341. if (index !== -1) {
  342. // 修改对应key的值
  343. this.columnList[i][index][key] = value;
  344. targetItem = this.columnList[i][index];
  345. found = true;
  346. break;
  347. }
  348. }
  349. if (found && targetItem) {
  350. // 修改父组件的数据中的对应id的条目
  351. // #ifdef VUE2
  352. const valueIndex = this.value.findIndex(val => val[this.idKey] == id);
  353. if (valueIndex !== -1) {
  354. let data = this.cloneData(this.value);
  355. data[valueIndex][key] = value;
  356. this.$emit('input', data);
  357. }
  358. // #endif
  359. // #ifdef VUE3
  360. const modelValueIndex = this.modelValue.findIndex(val => val[this.idKey] == id);
  361. if (modelValueIndex !== -1) {
  362. let data = this.cloneData(this.modelValue);
  363. data[modelValueIndex][key] = value;
  364. this.$emit('update:modelValue', data);
  365. }
  366. // #endif
  367. }
  368. }
  369. }
  370. }
  371. </script>
  372. <style lang="scss" scoped>
  373. .u-waterfall {
  374. @include flex;
  375. flex-direction: row;
  376. align-items: flex-start;
  377. }
  378. .u-column {
  379. @include flex;
  380. flex: 1;
  381. flex-direction: column;
  382. overflow: hidden;
  383. /* #ifndef APP-NVUE */
  384. height: 100%;
  385. /* #endif */
  386. // 添加列之间的间距
  387. &:not(:first-child) {
  388. margin-left: 10rpx;
  389. }
  390. }
  391. .u-image {
  392. /* #ifndef APP-NVUE */
  393. max-width: 100%;
  394. /* #endif */
  395. }
  396. </style>