라우팅 router.js로 분리

This commit is contained in:
ByungyeonKim
2021-12-06 21:27:09 +09:00
parent 818aee8d87
commit 067f55da22
2 changed files with 40 additions and 38 deletions

View File

@@ -2,11 +2,10 @@ import './index.css';
import store from './store.js';
import Header from './components/header.js';
import Home from './components/home.js';
import Contents from './service/contents.js';
import Footer from './components/footer.js';
import Detail from './components/detail.js';
import router from './service/router';
import axios from 'axios';
const httpClient = axios.create({
@@ -71,42 +70,6 @@ const useLazyLoading = () => {
imgs.forEach((img) => io.observe(img));
};
const router = (path) => {
const routes = [
{ path: '/', view: Home() },
{ path: '/:category', view: 'Category' },
{ path: '/:category/:idx', view: 'Detail' },
];
let params = path.match(/\w+/g);
if (params === null) {
params = '/';
} else if (params.length === 1) {
routes[1].path = `/${params[0]}`;
} else if (params.length === 2) {
routes[2].path = `/${params[0]}/${params[1]}`;
}
const isMatched = routes.map((route) => {
return {
route,
result: location.pathname === route.path,
};
});
let matched = isMatched.find((match) => {
return match.result === true;
});
// 매치된게 없으면 Home 컴포넌트 반환
if (!matched) {
matched = routes[0].view;
}
return matched.route.view;
};
const render = (path) => {
const app = document.getElementById('app');

39
src/service/router.js Normal file
View File

@@ -0,0 +1,39 @@
import Home from '../components/home';
const router = (path) => {
const routes = [
{ path: '/', view: Home() },
{ path: '/:category', view: 'Category' },
{ path: '/:category/:idx', view: 'Detail' },
];
let params = path.match(/\w+/g);
if (params === null) {
params = '/';
} else if (params.length === 1) {
routes[1].path = `/${params[0]}`;
} else if (params.length === 2) {
routes[2].path = `/${params[0]}/${params[1]}`;
}
const isMatched = routes.map((route) => {
return {
route,
result: location.pathname === route.path,
};
});
let matched = isMatched.find((match) => {
return match.result === true;
});
// 매치된게 없으면 Home 컴포넌트 반환
if (!matched) {
matched = routes[0].view;
}
return matched.route.view;
};
export default router;