라우팅 router.js로 분리
This commit is contained in:
39
src/index.js
39
src/index.js
@@ -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
39
src/service/router.js
Normal 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;
|
||||
Reference in New Issue
Block a user