uniapp: webview全屏遮挡住状态栏vue2和vue3解决方案

在uniapp中使用web-view

<template>
 <view>
  <web-view :webview-styles="webviewStyles" src="https://uniapp.dcloud.io/static/web-view.html"></web-view>
 </view>
</template>

<script>
 export default {
  data() {
   return {
    webviewStyles: {
     progress: {
      color: '#FF3333'
     }
    }
   }
  }
 }
</script>

<style>

</style>

我们会发现webview会自动铺满整个屏幕,如果我们的导航栏是自定义的,那么就会被webview遮住。要使页面能够正常显示,我们需要用到两个Api:getAppWebviewgetSystemInfo

  • getAppWebview

uni-app 在 getCurrentPages()获得的页面里内置了一个方法 $getAppWebview() 可以得到当前webview的对象实例,从而实现对 webview 更强大的控制。

  • getSystemInfogetSystemInfo我们都很熟悉了,就是获取当前设备的具体信息。

下面来看具体的写法:

  • vue2写法
<template>
 <view>
  <web-view style="height: 100%;" :webview-styles="webviewStyles" src="http:"></web-view>
 </view>
</template>

<script>
 export default {
  data() {
   return {
    webviewStyles: {
     progress: {
      color'#07c160'
     }
    }
   }
  },
  
    onLoad() {
     let height = 0//定义动态的高度变量
     let statusbar = 0// 动态状态栏高度
     uni.getSystemInfo({ // 获取当前设备的具体信息
      success(sysinfo) => {
       statusbar = sysinfo.statusBarHeight;
       height = sysinfo.windowHeight;
      }
     });
     let currentWebview = this.$scope.$getAppWebview(); //获取当前web-view
     setTimeout(function({
      var wv = currentWebview.children()[0];
      wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度,单位为px
       top: statusbar, //此处是距离顶部的高度,应该是你页面的头部
       height: height - statusbar, //webview的高度
      })
     }, 200); //如页面初始化调用需要写延迟
    }

 }
</script>
  • vue3写法
            <script setup>
 import { ref, onMounted } from 'vue';
 const webviewStyles = ref({
   progress: {
     color'#07c160'
   }
 });
 onMounted(async () => {
   let height = 0;
   let statusbar = 0;
 
   // 使用 async/await 来获取系统信息
   const sysinfo = await uni.getSystemInfo();
   statusbar = sysinfo.statusBarHeight;
   height = sysinfo.windowHeight;
  //获取webview
  let pages = getCurrentPages();
   let page = pages[pages.length - 1];
   let currentWebview = page.$getAppWebview();
            setTimeout(function({
                    var wv = currentWebview.children()[0];
                    wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度,单位为px
                            top: statusbar, //此处是距离顶部的高度,应该是你页面的头部
                            height: height - statusbar, //webview的高度
                    })
            }, 200); //如页面初始化调用需要写延迟
 });
   </script>     

做一个记录,以防忘记!


原文始发于微信公众号(大前端编程教学):uniapp: webview全屏遮挡住状态栏vue2和vue3解决方案

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/224521.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!