라우팅 | Vue.js

공식 라우터

→ 대부분의 싱글 페이지 앱(SPA)의 경우, 공식적으로 지원되는 vue-router 라이브러리를 사용하는 것이 좋다.

간단한 라우팅 구성하기

매우 간단한 라우팅이 필요하다면 동적인 컴포넌트를 사용하고, 브라우저 hashchange 이벤트를 수신하거나 History API를 사용해서 현재 컴포넌트 상태를 업데이트할 수 있다.

<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

const currentPath = ref(window.location.hash)

window.addEventListener('hashchange', () => {
  currentPath.value = window.location.hash
})

const currentView = computed(() => {
  return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>

<template>
  <a href="#/">Home</a> |
  <a href="#/about">About</a> |
  <a href="#/non-existent-path">잘못된 링크</a>
  <component :is="currentView" />
</template>