vue.js编写移动端页面,检测旋转屏幕,横竖屏。

发布于 2022-09-06 15:08:29 字数 1469 浏览 22 评论 0

初学vue,想要在检测到旋转屏幕后显示遮罩层。
现在我的想法是在mounted时期添加监听屏幕旋转事件,如果检测到了,则修改data中的值isShowCover来改变v-show中的真假值,来达到显示隐藏遮罩层的目的。
但是mounted时期好像取不到data中的值。我是用alert来判断取不取的到值的.

this.isShowCover 是undefined
this.showCover() alert都不提示了。
this.$options.methods.showCover() alert也不提示了。

所以想问的是想要监听到旋转屏幕事件,这个事件应该加在哪里?检测到旋转屏幕事件后,怎么才能把isShowCover的值改变来显示隐藏遮罩层?data中的值大概是什么时候可以取到并且修改?

提前感谢下回答的大佬。

下面附主要代码。

<template>
<div v-show="isShowCover" style = "position:fixed;background:transparent;background:rgba(0,0,0,0.5);margin:auto;top:0;bottom:0;left:0;right:0">
          <img src="../../pic/rotatePic.png" style="width:200px;height:200px;margin:auto;top:0;bottom:0;left:0;right:0">
</div>
</template>
<script>
export default {
    data: () => ({
      isShowCover: false
    }),
    mounted() {
    window.addEventListener(
      "onorientationchange" in window ? "orientationchange" : "resize",
      function() {
        if (window.orientation === 90 || window.orientation === -90) {
            //想把下面的alert换成能够控制v-show的代码
            
          alert(
            this.$options.methods.showCover() +
              "横屏可能导致页面异常,建议竖屏操作!"
          );
          //alert("123");仅alert纯文本可以正常运行
        }
        //window.location.reload();
      },
      false
      );
    },
    methods:{
        showCover() {
          return "123";
        },
    }
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若沐 2022-09-13 15:08:29

listener 里的 function 的 this 不对吧, 指向的应该不是 vue 的 this, 换成() => 应该就好了.

<script>
export default {
    data: () => ({
      isShowCover: false
    }),
    mounted() {
    let self = this; // 这里
    window.addEventListener(
      "onorientationchange" in window ? "orientationchange" : "resize",
      function() {
        if (window.orientation === 90 || window.orientation === -90) {
            //想把下面的alert换成能够控制v-show的代码
            
          alert(
            self.$options.methods.showCover() +
              "横屏可能导致页面异常,建议竖屏操作!"
          ); // 这里用 this 作用域就不对了.
          //alert("123");仅alert纯文本可以正常运行
        }
        //window.location.reload();
      },
      false
      );
    },
    methods:{
        showCover() {
          return "123";
        },
    }
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文