npm 사용시
npm install vue-router
yarn 사용시
yarn add vue-router
import { createWebHistory, createRouter } from 'vue-router';
import ClassMain from '../components/ClassMain.vue'
const router = new createRouter({
history: createWebHistory(),
base: process.env.BASE_URL,
routes:[
{
// path: URL 경로
// name: 라우트명
// component: 컴포넌트 경로
path:'/',
name: ClassMain,
component: ClassMain
}, {
path:'/classes/register',
name: ClassRegister,
component: ClassRegister
},{
//....
}
]
}]
export default router;
import { createApp } from 'vue'
import router from './routes/index'
import App from './App.vue'
const app = createApp(App).use(router)
app.mount('#app')
<template>
<div id="app">
<router-view :key="$route.fullPath"></router-view>
</div>
</template>
: 버튼 클릭시 페이지 이동
component/ClassMain.vue
this.$router.push({path:'이동할 URL', query: {data: data}, params: {data: data}}
: URL 이동할 때 사용하며 히스토리 스택에 쌓여 뒤로가기 버튼 클릭시 이전 URL로 이동
- path : 이동할 URL
- query: 전달할 데이터, 경로에 노출됨
- params: 전달할 데이터, 경로에 노출되지 않음
- this.$route.query.data : 이전 component에서 위의 메소드를 통해 넘겨받은 query에 접근
<script>
....
methods:{
....
},// 페이지 이동
ClassRegister() {
//path: 이동할 경로, 라우터에서 등록한 경로 입력
//query: 해당 페이지로 넘겨줄 인자
this.$router.push({path : '/classes/register',
query : {user_id: this.$route.query.user_id}});
}
}
....
</script>
<template>
<button style="cursor:pointer" type = "button" @click="ClassRegister()" id="delete_btn">삭제</button>
</template>
router-link : 라우터로 등록된 해당 url로 이동
- to: 이동할 URL
<template>
<li><router-link to='/login'><img id="logout_img" src="../../icons/logout.svg" alt="logout"></router-link></li>
</template>
npm install axios
yarn add axios
import { createApp } from 'vue'
import router from './routes/index'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App).use(router)
app.config.globalProperties.axios = axios;
app.mount('#app')
<script>
import axios from 'axios'
export default {
name: 'ClassMain',
data : function(){
return {
classList : [],
};
},
methods: {
getClassList() {
// Http get 메서드로 요청
axios.get('백엔드 경로'
).then((res)=>{
// 통신 성공시
this.classList = res.data
console.log(this.classList)
}).catch((err) => {
// 통신 실패시
console.log(err);
});
}
}
}
</script>
axios.get(URL+query) : 서버로 부터 데이터를 가져옴
axios.post(URL+query, {data: 'data'}) : 서버에 데이터를 전달함
axios.put(URL+query, {data: 'data'}) : 서버에 특정 데이터를 수정하도록 요청함
axios.delete(URL+query) : 서버에 특정 데이터를 삭제하도록 요청함