一、个人分析
简述
这个问题其实就是计算已经存在的组件的高度和整个页面可用的总高度,算出高度后再动态绑定style样式达到自适应。(总高度-其他组件高度 = 局部scroll-view 自适应的高度)
问题
首先,遇到这个问题,我的解决方法是搜索类似问题,寻找答案,在找的过程中,有几个问题让我迷惑
- 计算高度的这个方法应该写在什么地方?onReady(),computed(),还是methods里?
- 怎么计算页面可用总高度?组件的高度怎么获得?
- 怎么动态绑定高度?
解答
1.computed()属于vue框架中的知识,我们在运算时,会习惯在模板中运算,而这样会增加模板的负担,因而产生了用于实现简单运算来计算属性的computed()方法,具体了解参考文章:https://cn.vuejs.org/v2/guide/computed.html,而写在onReady()中能使每次加载时都计算一次高度,更新高度。所以我用的是onReady()
2.获取设备可用屏幕总高度。
uni.getSystemInfo({
success: function (res) {
var windowHeight= res.windowHeight;
}
});
获取组件高度,使用Id选择器,多组件的话就叠加使用
let view = uni.createSelectorQuery().select("#head");
view.boundingClientRect(data => {
_this.topHeight = data.height;
}).exec();
3.动态绑定高度
<scroll-view id="scrollbody" scroll-y="true" :style="{height:scrollerHeight}"></scroll-view>
数据
data() {
return {
phoneHeight: 0, //屏幕可用高度
topHeight: 0, //滑块上方高度
bottomHeight: 0, //底部高度
scrollerHeight: "",
}
},
二、完整代码展示
前端代码
<template name="home">
<view>
<view id="head">
<view class=" bg-white grid col-4 padding-lr-sm no-border margin-bottom-xs margin-lr-xs">
<view class="padding-sm animation-slide-bottom" :style="[{