通过监听页面宽度切换移动端和PC端

29 篇文章 1 订阅
<template>
  <div id="app" v-if="showCard">
    <HeadNav></HeadNav>
    <router-view v-cloak v-if="isRouterAlive" />
    <!-- 返回顶部组件 -->
    <scroll-to></scroll-to>
    <!-- 客服 -->
    <div class="kefu" @click="contact">
      <img src="@/assets/imgs/kefu.png" />
      <span>在线咨询</span>
    </div>
  </div>
</template>
<script>
import HeadNav from "@/components/header.vue";
import scrollTo from "@/components/scrollTo.vue";
export default {
  components: { HeadNav, scrollTo },
  data() {
    return {
      isRouterAlive: true, //控制视图是否显示的变量
      screenWidth: document.body.clientWidth,
      showCard: false, //控制页面的显示
    };
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        let that = this;
        setTimeout(function () {
          // 打印screenWidth变化的值
          let w = that.screenWidth;
          if (w <= 1080) {
            //手机端
            location.href = "移动端";
          } else {
            location.href = "PC端";
          }
          that.timer = false;
        }, 400);
      }
    },
  },
  created() {
    if (this._isMobile()) {
      //手机端
      location.href = "移动端";
    }
  },
  methods: {
    // 在线咨询
    contact() {
      window.open(
        "####",
        "_blank",
        "height=600, width=600, top=50, left=50, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no"
      );
    },
    //Vue判断设备是移动端还是pc端
    _isMobile() {
      let flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      return flag;
    },
  },
  mounted() {
    function checkIE() {
      return (
        "-ms-scroll-limit" in document.documentElement.style &&
        "-ms-ime-align" in document.documentElement.style
      );
    }
    if (checkIE()) {
      window.addEventListener(
        "hashchange",
        () => {
          var currentPath = window.location.hash.slice(1);
          if (this.$route.path !== currentPath) {
            this.$router.push(currentPath);
          }
        },
        false
      );
    }
    if (this._isMobile()) {
      //手机端
      location.href = "移动端";
    }
    const that = this;
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    };
    //显示页面
    this.showCard = true;
  },
};
</script>

<style scoped lang="scss">
[v-cloak] {
  display: none;
}
</style>


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值