<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<style>
/*.router-link-active{*/
/*color: red;*/
/*}*/
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<router-link to="/home">主頁</router-link>
<router-link to="/news">新聞</router-link>
<!--顯示路由內容-->
<router-view></router-view>
</div>
</body>
<script>
// 1.定義組件
var home = {
template: '<h1>home</h1>'
};
var news = {
template: '<h1>news</h1>'
};
//2. 配置路由
const routes = [
{path:'/home',component:home},
{path:'/news',component:news},
{path:'*',redirect:'/home'}
];
//3. 配置路由實例
const router = new VueRouter({
routes,
mode:'history', //切換不一樣的模式
linkActiveClass: "active" //動態類
});
//4. 掛載
new Vue({
el: "#app",
router,
})
</script>
</html>
- hash —— 即地址欄 URL 中的 # 符號(此 hash 不是密碼學裏的散列運算)。
好比這個 URL:http://www.abc.com/#/hello,hash 的值爲 #/hello。它的特色在於:hash 雖然出如今 URL 中,但不會被包括在 HTTP 請求中,對後端徹底沒有影響,所以改變 hash 不會從新加載頁面。
- history 模式下,前端的 URL 必須和實際向後端發起請求的 URL 一致,如 http://www.abc.com/book/id。若是後端缺乏對 /book/id 的路由處理,將返回 404 錯誤。Vue-Router 官網裏如此描述:「不過這種模式要玩好,還須要後臺配置支持……因此呢,你要在服務端增長一個覆蓋全部狀況的候選資源:若是 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面。」