#### 定義一個路由
- 實例化一個路由並設置路由映射表
- 實例化里面第一個參數 routes 路由映射表
- routes 里面參數
- path 路由的路徑
- component 路由對應的組件
- 第二個參數 我們選中的樣式指定
- 一般我們用默認樣式router-link-active就行
- 指定樣式語句 linkActiveClass:"aaa",
```
let routes=[
{
path:"/home",
component:home
}
]
const router=new VueRouter({
routes:routes,
linkActiveClass:"aaa",
})
```
- 實例化路由后,我們需要把路由掛載到Vue實例上
-
- router路由會在實例中提供兩個屬性
- this.$route(屬性)
- this.$router(方法);
```
let vm=new Vue({
el:"#app",
router:router
})
```
實例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .active{ color:red; } /*當選中時候生效, / /list /add 只要以/開頭就會生效*/ /*.router-link-active{*/ /*color:red;*/ /*}*/ /*當路徑和名稱相同時候,才會生效,一般用這個 */ /*.router-link-exact-active{*/ /*color:blue;*/ /*}*/ </style> </head> <body> <div id="app"> <router-link to="/home" tag="li">去首頁</router-link> <router-link to="/list" tag="li">去list頁</router-link> <router-view></router-view> </div> </body> <script src="node_modules/vue/dist/vue.js"></script> <script src="node_modules/vue-router/dist/vue-router.js"></script> <script> //定義兩個組件 let Home={ template:"<div>Home</div>" }; let List={ template:"<div>List</div>" } // 配置一個路由映射表,const防止被修改 const routes=[ { //定義路徑/home和對應Home的組件 path:"/home", component:Home }, { //定義路徑/list和對應List的組件 path:"/list", component:List } ]; //構建一個路由容器VueRouter let router=new VueRouter({ //默認路由就是hash規格的,將路由映射表賦值給routes屬性 routes:routes, //更改選中時候的樣式名稱 linkActiveClass:'active', // mode:'history' //使用h5api的history.pushstate()來改變路徑 }); // 使用這個路由 let vm=new Vue({ el:"#app", // 將 router賦值給router屬性,這時候就引入到實例中, // 會在實例中提供兩個屬性this.$route(屬性),this.$router(方法); router:router }) </script> </html>