Nuxt判断手机端还是电脑端

nuxt.js 同一路由pc和移动端

(1) 在pages下创建文件夹index

(2) 在index文件夹下创建三个文件 index.vue 、 indexPc.vue 、 indexMobile.vue

(3)文件内容。

1、index.vue

<template>
  <div>
    
    <component :is="component"></component>
    
  </div>
</template>

<script>
import Pc from "./Pc.vue";
import Modile from "./mobile/index.vue";
export default {
  transition: 'index',
  components: {
    Pc,
    Modile,
  },
  data() {
    return {
      component: "Pc",
      screenWidth: "",
    };
  },
  methods:{
    _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;
    },
  },
  watch: {
    screenWidth(val) {
      this.component = val < 800 ? "Modile" : "Pc";
    },
  },

  mounted() {
    if (this._isMobile()) {
      // alert("手机端");
      this.component = "Modile";
      // this.$router.push({ name: "index_p"});
    } else {
      this.component = "Pc";
      // alert("pc端");
      // this.$router.replace("/index");
    }
    const that = this;
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    };
  },
};
</script>

2、indexPC.vue

3、 indexMobile.vue 

(4) 记得在.nuxt ->router.js下改变路由
path: “/index” 改为 path: “/”,

案例:


 在.nuxt的router.js对应的路由应该这样设置

 

就能正常显示手机端和电脑端了 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪先生5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值