[vue.js] vue component, router와 예제

jihun Choi·2023년 9월 25일
0
post-thumbnail

안녕하세요 오늘은 뷰 component와 router를 구현 하는 법에 대해 알아보고 간단한 예제를 구현해 보도록 하겠습니다.

😎 vue router 란?

뷰 라이브러리를 이용하여 싱글 페이지 어플리케이션을 구현할 때 사용하는 라이브러리로 뷰 페이지 이동을 구현 할수 있습니다.


먼저 뷰 라우터를 구현하기 위해 인텔리제이 터미널로 라우터를 다운받아 줍니다

  • 라우터를 다운받는 명령어

     npm i --save vue-router

예제를 구현하기 위해 백앤드에서 데이터를 http 통신 할수 있는 axios 도 다운받아 줍니다

  • axios를 다운받는 명령어

      npm install axios


백앤드와 통신하기 위해 vue 모듈에 vue.config.js 파일을 만든 후 proxy를 설정해줍니다

  • vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  outputDir: "../src/main/resources/static",
  devServer: {
    port: 8082,
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        changeOrigin: true
      }
    }
  },
  lintOnSave:false
})

proxy 설정은 특정 url로 호출이 될경우 백앤드로 url을 넘겨주는 역할을 합니다 저는 데이터를 호출하기 위해 '/api'로 url이 호출될 경우 백앤드로 넘겨주도록 설정했습니다

router를 선언하기 위해 src 폴더에 routes 라는 폴더를 생성하고 하위에 index.js라는 파일을 만들어 주었습니다


  • index.js
import { createWebHistory, createRouter } from 'vue-router'
import RouterTest from '../components/board/RouterTest.vue'; //게시판 리스트 컴포넌트 호출
import Index from '../components/board/Index.vue'; //게시판 리스트 컴포넌트 호출

const router = createRouter({
    history: createWebHistory(),
    routes : [
        {
            path:'/',
            name:"Home",
            component: Index
        }
        ,{
            path:'/2',
            name : "RouterTest",
            component:RouterTest
        }
    ]
})

export default router;

'/' url로 호출될경우 /src/components/board/Index.vue가 나오도록 구현하고 '/2' url로 호출될경우 /src/components/board/RouterTest.vue가 나오도록 구현하였습니다.

처음 vue.js 초기화면을 띄울때 src 하위에 있는 index.js를 호출하는데 여기서 router를 등록할수 있습니다


  • index.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './routes/index'; //설정 라우터 호출

createApp(App).use(router).mount('#app')

index.js가 호출된 후 App.vue가 화면에 노출되는데 여기서 화면 템플릿을 구현할수 있습니다

  • App.vue
<template>
  <Header />
  <router-view></router-view>
</template>

<script>
import Header from './components/common/Header.vue'; //설정 라우터 호출
export default {
  name: 'App',
  components: {
    Header
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

헤더를 생성하여 넣어주고 router-view 태그를 통해 url이 변경될때 마다 동적으로 컴포넌트를 넣어주도록 구현하였습니다


Index.vue

<template>
  <div>{{var1}}</div>
  <button v-on:click="toggle"> 클릭! </button>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Home',
  data(){
    return {
      var1 : null
    }
  },
  methods : {
    toggle : function (){
      this.var1 *= 2;
    }
  },
  created() {
    axios.get("http://localhost:8082/api/getInt")
        .then(response => {
          this.var1 = response.data;
        })
        .catch(function (error) {
          // 에러인 경우 실행
          console.log(error);
        })
        .then(function () {
          // 항상 실행
        });
  }
}
</script>

<style scoped>

</style>

axios.get 메소드를 사용하여 백앤드단에서 getInt 메소드를 호출하여 var1 데이터에 값을 넣어줬습니다 버튼을 클릭할때마다 var1값이 2배로 증가하여 보여질수 있도록 구현하였습니다

위 사진과 같이 버튼 클릭시 2배로 증가하는것을 확인할수 있었습니다


RouterTest.vue

<template>
  <div>router 테스트 입니다</div>
</template>

<script>
export default {
  name: 'RouterTest'
}
</script>

<style scoped>

</style>

router 테스트를 위해 RouterTest.vue를 만들어 '/2' url을 호출할 경우 RouterTest.vue가 정상 노출 되는지 확인해 보았습니다

url 호출 결과 정상적으로 노출된것을 확인할수 있었습니다 다음번엔 더 재미있는 소재로 찾아뵙겠습니다 감사합니다.

profile
성장을 위해 열심히 노력하는 개발자 입니다

0개의 댓글