Vue 3 example using router in one HTML file without build step.
Last active
October 30, 2024 00:21
-
-
Save tbreuss/a8974449bac9ec67d95d535d73305200 to your computer and use it in GitHub Desktop.
Vue 3 router example in one HTML file without build step
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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