前言:
本人是实打实的后端,今日被迫开始编写前端项目,于是开启一边学习一边实际上手项目的过程,专栏《UniApp工作学习笔记》将专用于记录开发过程中的Bug及解决方案,作为后端,真想唾弃JS一万遍,可能是我实在是不习惯使用这种语言或者Uniapp的框架,习惯了你需要什么就定义什么随手引用的C#,猛的上手Uniapp极其不习惯,特别是蹩脚的代码提示联想以及垃圾的报错方式。
框架:Uniapp
IDE:HBuilder X 3.7.3
日期:2023/3/14 周二
(文中代码块均为回忆或二次处理后的代码块,可能存在有些地方比如变量名有问题或者个别语法错误,发之前我会大概速览一遍,不过没有错误提示,有看出的请指正,海涵!)
首先,贴出一直无法实现部分的代码(整个过程将以半教程半过程的方式记录,以提供一种解决Bug的思路):
<template>
<view class="main-hover" :style="{height:screenHeight1}" >
</view>
</template>
<script>
export default{
data(){
return{
screenHeight:0,
};
},
onLoad() {
uni.getSystemInfo({
success:function(res){
this.screenHeight = res.screenHeight;
}
})
},
methods:{
}
}
</script>
<style>
.main-hover{
background-size: 100%;
width: 100%;
min-height: 400px;
background: aqua;
}
</style>
因为百度到了这种获取并动态修改高度的方式,于是按照其方法CV并修改,结果Debug运行时没有任何效果!
甚至
:style:"{height:screenHeight}"
此处的height直接就没有,联想中出现的就俩,一个innerHeight,一个outerHeight,我一度怀疑这玩意有严重问题(→_→)
我第一时间想到的问题就是生命周期,一开始以为Ready在Load之前,结果一查,发现Load在前,于是我祭出Log大法,我尼玛,我先看看这个screenHeight到底有没有赋值成功
于是在赋值后添加了Log,方法变成了这样
onLoad(){
uni.getSystemInfo({
success:function(res){
this.screenHeight = res.screenHeight;
console.log(this.screenHeight);
}
})
},
原以为他要给我报个Current的值,结果log出来和实际尺寸一模一样,Woc,搞我啊?那aqua的尺寸明明就400,你给我打出来个480?哎,问万能的度娘吧。
百度上一搜,我的天,这Uniapp看样子应该都是大佬,好像从来没人遇到过这种低端问题,说的最多的竟然是v-bind后面的height带不带引号
:style"{'height':screenHeight}"
或者这样
:style"{'height':screenHeight + 'px'}"
又或者这样
:style"{height:screenHeight + 'px'}"
哎,从大神们的代码不管咋看好像我这个怎么改都没问题,但是这个aqua他就是不往下挪动哪怕1px,真无语,接着我就开始想,有没有可能时获取时的方法问题,因为再次之前我看到一个帖子介绍了三种获取尺寸的方法,于是我换了一种方式:
<template>
<view class="main-hover" :style="{height:screenHeight1}" >
</view>
</template>
<script>
export default{
data(){
return{
screenHeight:0,
};
},
onLoad() {
uni.getSystemInfo({
success:function(res){
this.screenHeight = res.screenHeight;
}
})
this.screenHeight = uni.upx2px(uni.getSystemInfoSync().windowHeight);
},
methods:{
}
}
</script>
<style>
.main-hover{
background-size: 100%;
width: 100%;
min-height: 400px;
background: aqua;
}
</style>
可以看到,我在下面加了一句
this.screenHeight = uni.upx2px(uni.getSystemInfoSync().windowHeight);
Ctrl + S,卧槽,泪奔了,竟然变大了……
之后我又去搜索到底为啥,凭啥加个Sync就能出来,查到一个原因是:
getSystemInfo()方法必须写进自定义函数里,并需要将需要的数值返回,不然即为无效。
也就是说,如果你非得用getSystemInfo() ,不用不行,那就得写成这样:
onLoad() {
this.screenHeight = this.getData()
console.log(this.wagesheight);
},
methods: {
getData(){
var result = 0;
uni.getSystemInfo({
success: function(res) {
console.log(res.windowHeight);
result = uni.upx2px(res.windowHeight);
}
});
return result;
}
总结:
坑,真坑,不报错、没联想,值还给照常赋,就是不让你用,无语透了,大神别喷,毕竟刚开始,此文写给同样摸不着脑袋的朋友。