본문 바로가기

Vue 실습

Today I Learned : Vue.js 랜더링시 해결 과정 중 배운 것 정리

728x90

 

어제 Do it! 프런트엔드 UI 개발 with Vue.js의 구현을 모두 끝냈다. 해당 책을 기획이자 디자인, 와이어프레임이라고 생각하고 했던 사이드 프로젝트가 끝이 났다.

그리고 오늘부터 좀 더 프런트엔드답게 고정 데이터인 부분을 => axios 호출해서 가져오는 형태 또는 모듈화 및 추상화를 넣어주는 리팩토링을 시작하고자 했다.

 

과정에서 몇 가지의 문제점이 생겼습니다. 또 해결해 가면서 배운 것들을 정리하는 과정을 가져볼까 합니다.

 


 

 

0. 이전에 구현 중 localhost:5147/ 로 이동시 index.vue로 이동하게 라우팅이 되어 있었습니다. 하지만 index.vue는 아래와 같이 구현되어 있었습니다.

 

<template>
  <div>
    <section id="wrap" class="subPageMain">
      <h1 class="blind">웹사이트 제목</h1>
      <Header></Header>
      <section id="container">
        <RouterView />
      </section>
      <Footer></Footer>
    </section>
  </div>
</template>

<script setup lang="ts">
import Header from './components/Header.vue'
import Footer from './components/Footer.vue'
</script>

 

이렇기 때문에 path: "/"으로 갈 경우 content가 비어있는 페이지가 바로 보이게 되죠. 

 

0. 해결: 리다이렉트를 이용해서 문제를 해결

 

const withPrefix = (prefix: any, routes: any) =>
  routes.map((route: any) => {
    route.path = prefix + route.path
    return route
  })

const pageRouter = {
  path: '/',
  name: 'layout',
  component: () => import('@/layout/index.vue'),
  children: [
    {
      path: '/',
      redirect: '/main' // <=== 경로로 접속 시 /main으로 리다이렉트!!
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main.vue')
    },
    ...withPrefix('/book', [
      {
        path: '/',
        component: () => import('@/views/Books/Books.vue')
      },
      {
        name: 'book',
        path: '/:tabId',
        component: () => import('@/views/Books/Books.vue')
      }
    ]),
    {
      path: '/reference',
      name: 'reference',
      component: () => import('@/views/Reference/reference.vue')
    },
    {
      path: '/movieclass',
      name: 'movieclass',
      component: () => import('@/views/MovieClass/movieclass.vue')
    },
    {
      path: '/classample',
      name: 'classample',
      component: () => import('@/views/ClassSample/classsample.vue')
    },
    {
      path: '/company',
      name: 'company',
      component: () => import('@/views/Company/company.vue')
    }
  ]
}

export default pageRouter

 


 

1. axios를 호출하려고 하는데 백엔드 서버가 없는 상황.. express.js를 배웠지만 이거 리팩토링 학습하자고 그걸 하기에는 배보다 배꼽이 더 큰 느낌... 해서 mock 서버를 만드는 법을 배웠는다. - json.server 이용!

 

1-1. json-server를 설치하는 법

yarn global add json-server를 해도 되지만, 만약에 여러분이 npm을 사용하는 경우엔 제대로 작동하지 않을 수 도 있습니다.

$ npm i -g json-server

 

설치가 완료되었으면, fake-server라는 디렉터리를 만들고, 그 안에 db.json이라는 파일을 만드세요.

$ mkdir fake-server
$ touch db.json

 

db.json의 파일 내용은 다음과 같이 memo라는 배열을 입력해 주시면 되겠습니다:

db.json

{
  "data": [
      {
          "id": 1,
          "title": "first data title",
          "body": "first data content"
      }
  ]
}

 

그다음에, fake-server 디렉터리에서 다음 명령어를 통하여 서버를 실행하세요

json서버가 db.json을 바라보겠다. 포트 3001을 이용해서 대충 이렇게 이해하고 쓰고 있습니다.

또한 json서버를 라우팅 하고 싶을 때는

$ json-server --watch db.json --port 3001

 

아래 코드와 같이 할 수 있습니다.

json-server --watch data1.json --routes routes1.json --port 3001
json-server --watch data2.json --routes routes2.json --port 3002

// example routes1
{
  "/posts": "/posts",
  "/comments": "/comments"
}

// example data1.json
{
  "posts": [
    { "id": 1, "title": "Post 1" },
    { "id": 2, "title": "Post 2" }
  ],
  "comments": [
    { "id": 1, "text": "Comment 1" },
    { "id": 2, "text": "Comment 2" }
  ]
}

 

3. axois로 호출하고 응답받은 json 데이터 NewBooks.it, NewBooks.sicence.. 이렇게 있는 형태이고, it, service만 string으로 받아서 데이터를 치환하고 싶다면? 대괄호 표기법을 써서 해결해 보자!

const addContent = (newBookTitleName: string, index: number) => {
  showBookNewBook.value = []
  showBookNewBook.value = (Newbooks.value as any)[newBookTitleName]; // Push the new data to content
  isActiveNumber.value = index // Reset the active index
}

 

 

4. json 데이터를 주석표시해서 정보를 전달하고 싶을 때가 있을 것이다. 그럴 때는 이런 방법을 사용한다.

 

{    
     "Newbooks" : {
      "__comment__": "책 카테고리 탭에 따른 다른 종류의 책 데이터 모음", <== 요런식으로 주석표시
      "Newbooks": [ {
        "imgurl": "/images/books_image/book01.jpg",
        "name": "Do it! 웹 사이트 따라 만들기",
        "subdec": "HTML, CSS, 자바스크립트 문법서는 공부했지만, 웹 사이트를..."
      },
....

 

 


후기

 

이만 main.vue를 리팩토링 하면서 문제점을 만나고

해결하던 과정에서 배운 정리 목록들을 마치고자 한다.

아직 리팩토링이 끝나지 않았으므로 계속 올릴 예정이다.

728x90