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对应的路由应该这样设置

 

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

Logo

前往低代码交流专区

更多推荐