鍍金池/ 問答/網(wǎng)絡安全  HTML/ vue.js編寫移動端頁面,檢測旋轉屏幕,橫豎屏。

vue.js編寫移動端頁面,檢測旋轉屏幕,橫豎屏。

初學vue,想要在檢測到旋轉屏幕后顯示遮罩層。
現(xiàn)在我的想法是在mounted時期添加監(jiān)聽屏幕旋轉事件,如果檢測到了,則修改data中的值isShowCover來改變v-show中的真假值,來達到顯示隱藏遮罩層的目的。
但是mounted時期好像取不到data中的值。我是用alert來判斷取不取的到值的.

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

所以想問的是想要監(jiān)聽到旋轉屏幕事件,這個事件應該加在哪里?檢測到旋轉屏幕事件后,怎么才能把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>
回答
編輯回答
玄鳥

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>
2018年1月18日 09:21