引入
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
1、創建路由實例
// 創建index路由實例 let index = { template: '#index' } // 創建mine路由實例 let mine = { template: '#mine', } // 1、創建路由實例 const router = new VueRouter({ })
2、創建映射關系
const router = new VueRouter({ // 2、創建映射關系 routes: [ { path: '/', // 路由重定向,即展示頁面為/時自動切換到index redirect: '/index' }, { path: '/index', component: index }, { path: '/mine', component: mine } ], })
3、建立聯系,將路由掛在在vue實例上
const vm = new Vue({ el: '#app', data: { }, // 3、建立聯系,將路由掛載在vue實例上 // router:router, // 簡寫router router, methods: { }, })
4、展示位置/聲明兩個組件
<div id='app'>
<router-link to='/index' tag='span'>去首頁</router-link>
<router-link to='/mine' tag='span'>去個人中心</router-link>
<!-- 4、展示位置 -->
<router-view></router-view>
</div>
<!-- 聲明兩個組件 -->
<!-- index首頁組件 -->
<template id="index">
<div>
<div>首頁</div>
</div>
</template>
<!-- mine個人中心組件 -->
<template id="mine">
<div>
<div>個人中心</div>
</div>
</template>
完整代碼展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
.router-link-active {
color: red;
font-size: 30px;
}</style>
</head>
<body>
<div id='app'>
<router-link to='/index' tag='span'>去首頁</router-link>
<router-link to='/mine' tag='span'>去個人中心</router-link>
<!-- 4、展示位置 -->
<router-view></router-view>
</div>
<!-- 聲明兩個組件 -->
<!-- index首頁組件 -->
<template id="index">
<div>
<div>首頁</div>
</div>
</template>
<!-- mine個人中心組件 -->
<template id="mine">
<div>
<div>個人中心</div>
</div>
</template>
<script>
// 創建路由實例
// 創建index路由實例
let index = {
template: '#index'
}
// 創建mine路由實例
let mine = {
template: '#mine',
}
// 1、創建路由實例
const router = new VueRouter({
// 2、創建映射關系
routes: [
{
path: '/',
// 路由重定向,即展示頁面為/時自動切換到index
redirect: '/index'
},
{
path: '/index',
component: index
},
{
path: '/mine',
component: mine
}
],
//增加選中效果,如果添加下面這句在style中應該使用.active改變樣式
//linkActiveClass: 'active'
})
const vm = new Vue({
el: '#app',
data: {
},
// 3、建立聯系,將路由掛載在vue實例上
// router:router,
// 簡寫
router,
methods: {
},
})
</script>
</body>
</html>
展示結果:


