기록하는 개발자

[vanillaJs] 프레임워크없이 SPA 만들기-2. 라우팅 페이지 구성 본문

Web/Javascript

[vanillaJs] 프레임워크없이 SPA 만들기-2. 라우팅 페이지 구성

밍맹030 2022. 9. 1. 16:37
728x90

https://mingmeng030.tistory.com/244

 

[vanillaJs] 프레임워크없이 SinglePageApplication 만들기-1. 라우팅 설정하기

폴더 구조 1. frontend 폴더 내부에 index.html 파일 생성 후 아래와 같이 구성 // index.html <!DOCTYPE html> SPA with no framework Home Posts Settings - url 이동에 사용하게 될 a 링크들에 대하여 data-li..

mingmeng030.tistory.com

↑위 글과 이어지는 내용이다

 

파일 구조

1. AbstractView.js 생성 후 아래와 같이 추상화된 view 작성

export default class {
  constructor() {}

  setTitle(title) {
    document.title = title;
  }
  async getHtml() {
    return "";
  }
}

 

2. Home.js, Post.js, Setting.js 생성 후 아래와 같이 AbstractView.js를 import 하여 작성

//home.js
import AbstractView from "./AbstractView.js";

export default class extends AbstractView {
constructor() {
      super();
    this.setTitle("Home");
  }
  //getHtml을 fetch, ajax 등을 통해 서버에서 가져올 수 있으므로 async 처리
  async getHtml() {
    return `
            <h1>This is home page</h1>
            <p>express yourself</p>
            <p>
                <a href="/posts" data-link>View recent posts</a>
            </p>
        `;
  }
}
// Post.js
import AbstractView from "./AbstractView.js";

export default class extends AbstractView {
  constructor() {
    super();
    this.setTitle("Post");
  }
  async getHtml() {
    return `
      <h1>Posts</h1>
      <p>this is posting page</p>
    `;
  }
}
// Setting.js
import AbstractView from "./AbstractView.js";

export default class extends AbstractView {
  constructor() {
    super();
    this.setTitle("Settings");
  }
  async getHtml() {
    return `
      <h1>Settings</h1>
      <p>this is setting page</p>
    `;
  }
}

 

3. index.js의 routes배열 내 view 수정

import Home from "./views/Home.js";
import Posts from "./views/Post.js";
import Settings from "./views/Settings.js";

const navigateTo = (url) => {…};

const router = async () => {
  const routes = [
    // 각 path의 view를 작성한 js 파일로 지정
    { path: "/", view: Home },
    { path: "/posts", view: Posts },
    { path: "/settings", view: Settings },
  ];
  const potentialMatches = routes.map((route) => {…});
  let match = potentialMatches.find(…);
  if (!match) {…};

  // 변수 view는 현재 location.pathname에 해당하는 route에 지정된 view를 저장
  const view = new match.route.view();
  // app의 innerHtml에 현재 view에 대한 html을 가져와 저장
  document.querySelector("#app").innerHTML = await view.getHtml();
};

window.addEventListener("popstate", router);
document.addEventListener("DOMContentLoaded", () => {…});

4. index.css 작성

 

5. Index.html 수정

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SPA with no framework</title>
    <link rel="stylesheet" href="./static/css/index.css" />
  </head>
  <body>
    <nav class="nav">…</nav>
    <div id="app"></div>
    <!-- js entry point -->
    <script type="module" src="/static/js/index.js"></script>
  </body>
</html>

- getHtml 함수를 통해 각 view의 html을 띄울 div 생성

- index.css link로 추가

 

결과 화면

 

참고 영상 : https://www.youtube.com/watch?v=WbbAPfDVqfY
728x90