Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Last active October 30, 2024 00:21
Show Gist options
  • Save tbreuss/a8974449bac9ec67d95d535d73305200 to your computer and use it in GitHub Desktop.
Save tbreuss/a8974449bac9ec67d95d535d73305200 to your computer and use it in GitHub Desktop.
Vue 3 router example in one HTML file without build step
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js CDN Test</title>
</head>
<body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app-basic">{{ message }}</div>
<hr>
<div id="app-router"></div>
<template id="about">
<h1>About</h1>
</template>
<template id="home">
<h1>Home</h1>
</template>
<template id="notFound">
<h1>404</h1>
</template>
<template id="app-router-inner">
<a href="#/">Home</a> |
<a href="#/about">About</a> |
<a href="#/non-existent-path">Broken Link</a>
<component :is="currentView"/>
</template>
</body>
<script>
const {createApp, ref, computed} = Vue
createApp({
setup() {
const message = ref('Hello World!')
return {
message
}
}
}).mount('#app-basic')
// ----------------------------------------------------------------------------------------------------------------
// Page Components
// ----------------------------------------------------------------------------------------------------------------
const Home = {
setup() {
},
template: '#home',
}
const About = {
setup() {
},
template: '#about',
}
const NotFound = {
setup() {
},
template: '#notFound',
}
// ----------------------------------------------------------------------------------------------------------------
// Routing
// ----------------------------------------------------------------------------------------------------------------
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
})
// ----------------------------------------------------------------------------------------------------------------
// Application
// ----------------------------------------------------------------------------------------------------------------
createApp({
setup() {
return {
currentView
}
},
template: '#app-router-inner'
}).mount('#app-router')
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment