·
1 min read

Vue Tip: Simple Routing Without Using External Libraries

Vue Tip: Simple Routing Without Using External Libraries Image

Usually, you would use a library like Vue Router to handle routing in your Vue.js application. However, if you want to keep things simple and avoid adding extra dependencies, you can implement basic routing functionality without using external libraries.

It can be achieved by using Dynamic Components and updating the current component state by listening to browser hashchange events or using the History API.

Here's a simple example of how you can implement routing without using external libraries in a Vue.js application:

Component.vue
<script setup lang="ts"> 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(() => routes[currentPath.value.slice(1) || '/'] || NotFound) </script> <template> <a href="#/">Home</a> | <a href="#/about">About</a> | <a href="#/non-existent-path">Broken Link</a> <Component :is="currentView" /> </template>

StackBlitz Example

You can try out this example on StackBlitz:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.