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

初学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>
阅读 8.7k
1 个回答

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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题