HarmonyOS 鸿蒙Next中【快应用】list案例分享

HarmonyOS 鸿蒙Next中【快应用】list案例分享

背景描述:

快应用中list组件中两个子组件,如何在一个list子组件高度固定的情形下,让另一个子组件可以铺满list组件剩余的高度?

解决方案:

可以通过getBoundingClientRect方法分别获取到list和第一个子组件的高度,然后相减得到剩余的高度,再设置给第二个子组件,这样即可将list组件剩余的高度都铺满。

示例代码:

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <list id="main" class="list">
      <list-item id="item" class="listitem" type="text">
        <text class="title">first listitem content</text>
      </list-item>
      <list-item type="list-item" style="height: {{seconditemheight}}px;background-color:green">
        <text class="title">second listitem content</text>
      </list-item>
    </list>
    <text class="title" onclick="custom">set height</text>
  </div>
</template>

<style>
  .container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .list {
    height: 80%;
    border: 1px solid #000000;
  }
  .title {
    font-size: 50px;
  }
  .listitem {
    height: 200px;
    background-color: #00ced1;
  }
</style>

<script>
  module.exports = {
    data: {
      componentData: {},
      seconditemheight: 0,
      listheight: 0,
      firstitemheight: 0,
    },
    onInit() {
      this.$page.setTitleBar({
        text: 'menu',
        textColor: '#ffffff',
        backgroundColor: '#007DFF',
        backgroundOpacity: 0.5,
        menu: true
      });
    },
    custom() {
      var that = this
      that.$element('main').getBoundingClientRect({
        success: function(data) {
          that.listheight = data.height;
        },
      });
      that.$element('item').getBoundingClientRect({
        success: function(data) {
          that.firstitemheight = data.height;
        },
      });
      setTimeout(() => {
        that.seconditemheight = that.listheight - that.firstitemheight
        console.log("this.seconditemheight ", that.seconditemheight)
      }, 50);
    }
  }
</script>

更多关于HarmonyOS 鸿蒙Next中【快应用】list案例分享的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS 鸿蒙Next中【快应用】list案例分享的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,快应用的list组件常用于展示数据列表。以下是一个简单的案例:

<template>
  <div class="container">
    <list>
      <list-item for="{{items}}" type="item" onclick="onItemClick">
        <text>{{$item.name}}</text>
      </list-item>
    </list>
  </div>
</template>

<script>
export default {
  data: {
    items: [
      { name: 'Item 1' },
      { name: 'Item 2' },
      { name: 'Item 3' }
    ]
  },
  onItemClick(event) {
    console.log('Clicked item:', event.detail.value);
  }
}
</script>

<style>
.container {
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>

此案例展示了如何使用listlist-item组件创建一个简单的列表,并处理点击事件。

回到顶部