说明
无需构建, 使用全局构建版本, 直接引入js文件即可使用Vue和Vue-router的方法.
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue router demo</title>
<script src="https://cdn.jsdelivr.net/npm/vue@3.2.1/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vue-router@4.0.15/dist/vue-router.global.prod.js"></script>
</head>
<body>
<div id="app">
{{ message }}
<index></index>
</div>
<template id="index">
<h1>Hello App!</h1>
<p>
<strong>Current route path:</strong> {{ $route.fullPath }}
</p>
<nav>
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</nav>
<main>
<router-view />
</main>
</template>
<template id="home">
<h2>Home</h2>
</template>
<template id="about">
<h2> About </h2>
</template>
<script type="text/javascript">
const IndexView = { template: '#index' }
const HomeView = { template: '#home' }
const AboutView = { template: '#about' }
App = Vue.createApp({
data() {
return {
message: 'Welcome'
}
},
components: {
'index': IndexView,
'home': HomeView,
'about': AboutView,
}
})
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
]
const router = VueRouter.createRouter({
// history: VueRouter.createMemoryHistory(), //切换组件,地址栏不会变化
history: VueRouter.createWebHashHistory(),
routes,
})
App.use(router)
App.mount('#app')
</script>
</body>
</html>
效果
{{ message }}
Hello App!
Current route path: {{ $route.fullPath }}