Front-End

[Vue.js] 컴포넌트를 렌더링하는 라우터(router) 와 삽질 중…….

vue.js의 라우터가 나에게 고통을 주고 있다. params를 이용한 값 전달에 문제가 있는 것 같다. 경로에 파라미터 값들을 노출하지 않기 위해서  router를 이용해 값을 전달하는 방법으로 params를 이용하고 있다.

 

params를 이용하는 경우 페이지 새로고침을 하거나 리로드 할 때 값이 유지되지 않는다는 점에 반드시 기억해야한다. 삽질하지 말아야한다.!!

 

params로 값을 넘길 경우 path정보를 router에 추가하면 안된다. 

 

다음은 vue.js에서 라우터를 구성한 샘플 스크립트이다.

[paths.js]

import testPaths from './testPaths';

function createSubRoute(area, path, view, name, propMeta, props, redirect) {
  if (name) {
    return {
      name: name || view,
      path,
      component: resovle => import(`../views/${area}/${view}.vue`).then(resovle),
      meta: propMeta,
      props,
      redirect,
    };
  }
  return {
    path,
    component: resovle => import(`../views/${area}/${view}.vue`).then(resovle),
    meta: propMeta,
    props,
    redirect,
  };
}

export default [
  {
    path: '/',
    redirect: { name: 'Login' },
  },
  {
    path: '/login',
    name: 'Login',
    view: 'Login',
  },
  {
    path: '/test',
    view: 'testLayout',
    area: 'test',
    children: mrPaths.map(path => createSubRoute('test', path.path, path.view, path.name, path.meta, path.props, path.redirect)),
  },
];

 

[testPaths.js]

/**
 * Define all of your application routes here
 * for more information on routes, see the
 * official documentation https://router.vuejs.org/en/
 */
export default [
  {
    path: '',
    view: 'Dashboard',
    meta: {
      requiresAuth: false,
    },
  },
  {
    path: 'dashboard',
    view: 'Dashboard',
    meta: {
      requiresAuth: false,
    },
  },
  {
    path: 'company',
    view: 'Company',
    name: 'Company',
    meta: {
      title: '고객사',
    },
  },
  {
    path: 'companydetail',
    view: 'CompanyDetail',
    name: 'CompanyDetail',
    meta: {
      title: '고객사 상세보기',
      isBackArrow: true,
    },
  },
];

 

[index.js]

import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
import store from '@/store';
import paths from './paths';

Vue.use(VueRouter);

function createRoute(path, view, name, area, propMeta, propChildren) {
  const areaURL = (area) ? 'views/layouts' : 'views';
  return {
    name: name || view,
    path,
    component: resovle => import(`../${areaURL}/${view}.vue`).then(resovle),
    meta: propMeta,
    children: propChildren,
  };
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: paths.map(path => createRoute(path.path, path.view, path.name, path.area, path.meta, path.children)).concat([{ path: '*', redirect: '/login' }]),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { selector: to.hash };
    }
    return { x: 0, y: 0 };
  },
});

function goNextPage(to, from, next) {
  axios.post('/business/selectUserModel.do').then((rs) => {
    const clsRow = rs.data;
    if (clsRow.returnCode === 'CERT_SUCCESS') {
      store.commit('setSubmitYn', 'N');
      next();
    } else if (clsRow.returnCode === 'CERT_FAIL') {
      next('/login');
    }
  });
}

// 새로고침을 통해 접근시 라우터 기반에서는 새로고침은 불필요하므로 이와같이 정의
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else if (to.path === '/test/') {
    goNextPage(to, from, next);
  } else {
    if (!store.getters.getUserInfo) {
      // alert('비정상적인 접근.메인으로 이동합니다.');
      next('/test/');
    }

    goNextPage(to, from, next);
  }
});

router.afterEach(() => {
});

export default router;

[main.js]

import Vue from 'vue';
import { Common } from '@/assets/lib/mixin/common';
import router from '@/router';
import store from './store';
import App from './App.vue';
import vuetify from './assets/plugins/vuetify';

Vue.config.warnHandler = function () {}; // 디버깅 모드에서 Vue-warn 오류로그 비활성화
Vue.config.productionTip = false;

let app;
if (!app) {
  Vue.mixin(Common);

  app = new Vue({
    vuetify,
    router,
    store,
    render: h => h(App),
  }).$mount('#app');
}

 

비슷한 기능을 하는 페이지가 2개있다. 

데이터 조회 리스트에서 상세정보 클릭 후 되돌아오기 버튼을 클릭하였을 경우, 

하나의 페이지는 조회가되는데, 다른 하나의 페이지는 파라미터 값 누락으로 조회가 되지 않아 몇일 째 삽질 중에 있다.

그런데, 조회가 되는 페이지마져 정상적으로 동작하는 것처럼 보일 뿐 문제가 있는 것 같다.

뒤로 돌아가기 버튼을 클릭시 this.$router.go(-1); 를 사용중에 있다.

methods: {
    back(){
      this.$router.go(-1);
      // const routeParams = this.$store.getters.getRouteParams(this.$route.name);
      // if(routeParams.proIds==='undefined' || routeParams.proIds ==='' ){
      //     this.$router.go(-1);
      // }else{
      //   this.$router.push({ name: 'PromoCont', params: { startDate: routeParams.startDate, proIds: routeParams.proIds } });
      // }
    },
}

히스토리 백으로 이전 페이지를 돌아가기를 했을 때 파라미터값 정보들 유지가 가능한가?? 내가 아는 웹페이지에서의 히스토리 백은 그러하지 않다. get방식(query를 이용하는 방식)이라면 가능하겠지만…..라우터에서 params를 이용하는 방식은 post방식과 유사해보인다. 로그를 찍어본 결과 되돌려 받지 못하고 있다.

 

params를 이용하여 보낸 값을 get하기 위해 this.$route.params를 이용하여 받을 수 있다. 가령 위의 back()메소드에서 startDate값을 가져오기 위해서는 this.$route.params.startDate 하면 가져올 수 있다.  url에 파라미터와 값이 보이지 않음으로 이쪽 분야를 모르는 사람들에게는 안전해보일 수 있다. 그러나 브라우저 상에서 개발자모드로 진입하면 모든 정보를 파악할 수 있다.

 

 

vue router로 데이터 전달하는 2가지 방법의 기초 지식이 필요하다면 아래 글을 참고하자

 

vue router로 데이터 전달하기 – This and That

vue router로 데이터 전달하기 by 동호 윤 · Published 2021년 02월 17일 · Updated 2021년 02월 18일 1. 두 가지 방법 vue router로 데이터를 전달하는 방법은 2가지가 있습니다. 2. 전달하기 {name: ‘Query’, query: {name:

www.youlook.co.kr

 

빨리 해결책을 찾아야한다. 이렇게 시간을 허비할 수 읎다.

 

[분석 내용 추가]

  • 뒤로 돌아가기시 this.$router.go(-1)를 할 경우 라우터를 거치지 않음으로 , this.$route.params 정보를 가져올 수 없다. (undefined)
  • params 방식이 아닌 query 방식으로 전달해도 어쟀든 라우터를 거치지 않음으로 $this.$route.query 정보 역시 가져올 수 없다. 
  • this.$router.push({ name: ‘CompanyDetail’, params: param, query: { searchStr: this.query.searchStr, calltime: moment(new Date()).format(‘YYYYMMDDhhmmss’) } });

그래서? 어떻게 해?

[해결방법]

https://playground.naragara.com/1654

 

[Vue.js] Vuex를 기본으로 구성한 프로젝트에서 URL의 파라미터 값들을 저장 후 필요시 호출하는 방

라우터를 사용하여 파라미터 값들을 전달하는 방법은 2가지가 있다. 하나는 params 방식이고 또 하나는 query를 사용하는 방식이다. 메인페이지에서 다른 페이지를 호출하여 페이지 이동이 발생했

playground.naragara.com

 

Leave a Reply

error: Content is protected !!