Skip to content
On this page

Routing

Official Router

For most Single Page Applications, it's recommended to use the officially-supported kdu-router library. For more details, see kdu-router's documentation.

Simple Routing from Scratch

If you only need very simple routing and do not wish to involve a full-featured router library, you can do so with Dynamic Components and update the current component state by listening to browser hashchange events or using the History API.

Here's a bare-bone example:

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

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">Broken Link</a>
  <component :is="currentView" />
</template>

Try it in the Playground

<script>
import Home from './Home.kdu'
import About from './About.kdu'
import NotFound from './NotFound.kdu'

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

export default {
  data() {
    return {
      currentPath: window.location.hash
    }
  },
  computed: {
    currentView() {
      return routes[this.currentPath.slice(1) || '/'] || NotFound
    }
  },
  mounted() {
    window.addEventListener('hashchange', () => {
		  this.currentPath = window.location.hash
		})
  }
}
</script>

<template>
  <a href="#/">Home</a> |
  <a href="#/about">About</a> |
  <a href="#/non-existent-path">Broken Link</a>
  <component :is="currentView" />
</template>

Try it in the Playground

Routing has loaded