前端小白的uni-app艰难学习智力
用到的主要原理有:
分页原理利用高度截取后台传过来的数据内容在uni-app中,有这样一个接口 通过它我们可以获取一些元素信息,比如宽高,下面是我需要获取的东西:
<view class="content-text" id="box" :style="{height: boxHeight + 'px'}"> <view id="data" :style="{top: -boxHeight * currentPage + 'px'}" > <rich-text :nodes="contentData"></rich-text> </view> </view>首先页面是全屏状态,id为box的view为小说内容的容器,id为data的view是小说内容 boxHeight: 容器高度 textHeight: 由小说内容撑开的高度
.content-text { width: 100%; height: 92vh; line-height: 26px; box-sizing: border-box; display: block; position: absolute; top: 4vh; z-index: 2; background-color: #fff9eb; overflow: hidden; #data { width: 100%; display: inline-block; position: absolute; left: 0; padding: 0 10px; box-sizing: border-box; z-index: 3; text-indent: 1.5em; } }首先给box一个初始高度为92vh,然后获取他的高度(单位为px),因为我设置的行高是26px,所以在下面的代码中我会通过这个行高26px重新计算容器高度,使它成为26的倍数,这样就不会出现露出一半行字的情况了
onReady() { var text = uni.createSelectorQuery().select('#data') var box = uni.createSelectorQuery().select('#box') var view = uni.createSelectorQuery().select('.story') box.boundingClientRect(data => { this.boxHeight = Math.floor(data.height / 26) * 26 // console.log('boxHeight', this.boxHeight) }).exec() text.boundingClientRect(data => { this.textHeight = data.height // console.log('textHeight', this.textHeight) }).exec() view.boundingClientRect(data => { this.viewWidth = data.width // console.log('viewWidth', data.width) }).exec() }然后在computed中计算一章切割后的页数
storyData () { // 章节信息 return this.$store.state.storyData }, contentData () { // 本章内容 return this.storyData.content }, pageNum () { // 单章总页数 return Math.ceil(this.textHeight / this.boxHeight) || 1 // return Math.ceil(this.data.length / this.pageSize) || 1 }然后就是在绑定跳到下一页(上一页)方法了,只要++(- -)this.currentPage(当前页码)就ok了!
使用该方法需要注意以下几点: 两个高度获取需要的onready中执行,onready之前的生命周期都是没用的! 需要和后台说好不要用br标签来换行,因为这样会导致高度计算不准确,最好是一个段落就是一对p标签