목차 - https://okane-on-cliff.tistory.com/227
vue-cli의 디렉터리 구조는 다음과 같다.
먼저 App.vue부터 작성을 시작해 본다.
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
}
</script>
App.vue는 라우터 뷰를 통해 전환되는 컴포넌트들만 출력한다.
메인 페이지 컴포넌트를 작성한다.
MainView.vue의 내용은 다음과 같다.
<template>
<div>
<h2>메인페이지</h2>
<input v-model="title"><br>
<input v-model="content"><br>
<button @click="sub">전송</button>
<hr>
<table>
<tr v-for="(article, idx) in articleList" :key="idx">
<td>{{ article.num }}</td>
<td><router-link :to="`/article/${article.num}`">{{ article.title }}</router-link></td>
</tr>
</table>
<button @click="local">로컬호스트로도 연결해보자</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
title: "",
content: "",
articleList: []
}
},
created() {
this.loadArticle();
},
methods: {
loadArticle() {
axios.get("http://3.38.178.54:9999/board/getList").then(({data}) => {
this.articleList = [];
for (var d of data) {
this.articleList.push(d);
}
})
},
async sub() {
await axios.post("http://3.38.178.54:9999/board/write", {
title: this.title,
content: this.content
})
this.loadArticle();
},
async local() {
axios.get("http://localhost:9999/board/getList").then(({data})=>alert(data))
}
},
};
</script>
<style>
</style>
여기서 router-link 의 속성 :to에는 " " 안에 백틱을 적어서 백틱안에 ${ }이 String이 되는 효과를 누려보자
router-link는 router/index.js에서 mapping된 주소로 컴포넌트를 꺼내준다.
router/index.js의 내용은 다음과 같다.
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'main',
component: () => import('@/views/MainView.vue')
},
{
path: '/article/:num',
name: 'article',
component: () => import('@/views/ArticleView.vue')
},
{
path: '/edit/:num',
name: 'edit',
component: () => import('@/views/EditView.vue')
}
]
const router = new VueRouter({
base: process.env.BASE_URL,
routes
})
export default router
path: '/article/:num', 이부분을 보면 :num은 변수같은 것으로 다른 값이 들어와도 /article로 연결된다. num은
<template> 에서는 {{$route.params.num}}으로 <script>에서는 this.route.params.num으로 접근할 수 있다.
또한 router.js에는 여러가지 알아야 될 것이 많다.
예를들 만한 코드들을 적어보면 이렇다.
const onlyAuthUser = (to, from, next) => {
alert("먼저실행됨")
};
const routes = [
{
path: '/a',
name: 'a',
component: () => import('@/views/a'),
redirect: "/community/list",
children: [
{
path: "/b",
name: "b",
beforeEnter: A,
component: () => import("@/components/b")
},
]
},
]
redirect속성은 path로 연결될때 바로 다른 path로 이동할 수 있게 해준다.
children 속성을 사용하면 router-view안에서 새로운 router-view를 만들 수 있게 해준다.
beforeEnter 속성을 사용하면 컴포넌트가 실행되기 전에 실행해준다 created()랑 비슷해 보이지만 router/index.js에서 기술했으니까 각 컴포넌트별로 created에 적을게 아니라 공통적인 created를 한번에 만들 수 있다는 점
마지막으로 파일 가장 위에 import ㅁㅁㅁ from '../../A.js'
같은 식으로 쓰면 메서드나 router요소를 나눠서 적을 수 도 있을 거같다 실험해보진 않았지만 다시 만든다면 시도해 볼것이다.