본문 바로가기
쬬의 Vue

[Vue] 모바일/웹 분기설정 정규식예제

by Joooooooo 2022. 8. 17.
반응형

환경 : Vue2 + vue-router@3.5.4 + vuex@3

 

main.js

const isMobileDevice =
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? true
    : false;
    
    
//전역설정

Object.defineProperty(Vue.prototype, "$isMobileDevice", {
  value: isMobileDevice,
});

//this.$isMobileDevice 로 활용이 가능하다

 


 

 

Test.vue

 if (this.$isMobileDevice === true) {
            url = res.data.mobile_url;
 } else {
            url = res.data.online_url;
}

 

또는 이렇게 router 설정에서 모바일 환경과 웹 환경설정 활용에 사용이 가능하다

 

router/index.js

import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "@/views/HomeView";

Vue.use(VueRouter);

let router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "HomeWeb",
      component: () => import("@/views/web/HomeWeb"),
      beforeEnter: (to, from, next) => {
        let mobile =
          /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
            navigator.userAgent
          );
        if (mobile === true) {
          next("/m");
        } else {
          next();
        }
      },
      meta: {
        requiresAuth: false,
        requiresAdmin: false,
      },
    },
    {
      path: "/m",
      name: "HomeMobile",
      component: () => import("@/views/web/HomeMobile"),
      beforeEnter: (to, from, next) => {
        let mobile =
          /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
            navigator.userAgent
          );
        if (mobile !== true) {
          next("/");
        } else {
          next();
        }
      },
      meta: {
        requiresAuth: false,
        requiresAdmin: false,
      },
    }]
})

 

반응형