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>


繁星coding
浏览 3853回答 1
1回答

富国沪深

listener 里的 function 的 this 不对吧, 指向的应该不是 vue 的 this, 换成() => 应该就好了.<script>export default {&nbsp; &nbsp; data: () => ({&nbsp; &nbsp; &nbsp; isShowCover: false&nbsp; &nbsp; }),&nbsp; &nbsp; mounted() {&nbsp; &nbsp; let self = this; // 这里&nbsp; &nbsp; window.addEventListener(&nbsp; &nbsp; &nbsp; "onorientationchange" in window ? "orientationchange" : "resize",&nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; if (window.orientation === 90 || window.orientation === -90) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //想把下面的alert换成能够控制v-show的代码&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.$options.methods.showCover() +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "横屏可能导致页面异常,建议竖屏操作!"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ); // 这里用 this 作用域就不对了.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //alert("123");仅alert纯文本可以正常运行&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //window.location.reload();&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; false&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; },&nbsp; &nbsp; methods:{&nbsp; &nbsp; &nbsp; &nbsp; showCover() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "123";&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript