通过监听页面宽度切换移动端和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
    评论
Vue 可以通过检测浏览器的 user agent(`navigator.userAgent`)来区分移动端和 PC 端。以下是一个简单的实现方法。 首先,在 Vue 组件中,可以使用通过 `mounted` 生命周期函数来监听页面的加载完成,然后访问全局的 `navigator.userAgent` 字符串: ```javascript mounted () { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { // 移动端逻辑 // 例如,在移动端监听 touchstart 事件 document.addEventListener('touchstart', this.handleTouchEvent) } else { // PC 端逻辑 // 例如,在 PC 端监听 keydown 事件 document.addEventListener('keydown', this.handleKeyDown) } } ``` 在上述代码中,我们通过正则表达式检测 `navigator.userAgent` 字符串中是否包含移动设备的关键字,例如 `"Android"`、`"iPhone"` 等。如果匹配成功,则可以判断为移动端。否则,就可以判断为 PC 端。 在移动端逻辑中,可以监听移动端的触摸事件(如 `touchstart`、`touchmove`、`touchend` 等)来实现相应的键盘事件监听。在 PC 端逻辑中,则可以监听键盘事件(如 `keydown`、`keyup` 等)。 最后,需要在组件销毁时,也就是通过 `beforeDestroy` 生命周期函数,移除事件监听器,以免造成内存泄漏: ```javascript beforeDestroy () { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { document.removeEventListener('touchstart', this.handleTouchEvent) } else { document.removeEventListener('keydown', this.handleKeyDown) } } ``` 通过以上逻辑,我们可以区分移动端和 PC 端,并实现相应的键盘事件监听
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值