u-waterfall.vue 15 KB

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