安裝vue-router
npm install vue-router --save
引入
import VueRouter from "vue-router"
Vue.use(VueRouter)
實例化router
var router = new VueRouter({
// ...
})
將實例化的 router 添加到 vue 的實例中
new Vue({
el:"#app",
router:router, //將實例化的 router 添加到 vue 的實例中
components:{ App },
template: '<App/>'
})
在實例化router中設置配置選項
import Apple from './components/Apple' //引入Apple組件
import Banana from './component/Banana' //引入Banana組件
var router = new VueRouter({
mode:"history",//切換到history模式,默認是hash模式:路由后面會加上一個’#‘符號
routes:[
{
path:'/apple/:color', //跳轉路徑 /:color->路由參數
component:Apple
},
{
path:'/banana',
component: Banana
}
]
})
設置 vue-router 的顯示位置,通過內置組件:<router-view></router-view>
頁面跳轉通過:<router-link :to={path:'apple'}>跳轉到蘋果頁面</router-link>
獲取參數
通過 this.$route.params 來進行獲取.
同樣也可以通過頁面來進行訪問: {{ $router.params.color }}
路由嵌套
通過children來添加配置參數
routes:[
{
path:"/dad",
component: Dad,
children:[
{
path:"son1", //注意不能帶斜杠
component:Son1
},
{
path:"son2",
component:Son2
},
]
}
]
最后注意需要在組件里加上<router-view></router-view>標簽
router-link組件
1.可以直接跳轉:
<router-link to="/apple">跳轉</router-link>
2.可以動態跳轉:
<router-link :to="{path:'apple'}">跳轉</router-link>
3.具名的路由:通過tag屬性將標簽轉換為li標簽
<router-link :to="{path:'apple'}" tag="li"></router-link>
命名路由
1.設置的時候可以直接給路由加上name屬性,然后在<router-link :to="{name:'applePage',params:{color:'red'}}">跳轉</router-link>里直接跳轉(params是路由參數)
routes:[
{
path:'/apple/:color', //跳轉路徑 /:color->路由參數
component:Apple,
name: 'applePage'
},
{
path:'/banana',
component: Banana
}
]
2.路由重定向
例:將"/"地址重定向到“/apple”
routes:[
{
path:"/",
redirect:"/apple"
},
{
path:'/apple/:color', //跳轉路徑 /:color->路由參數
component:Apple,
name: 'applePage'
},
{
path:'/banana',
component: Banana ,
alias:'bananas' //別名
}
]
linkActiveClass
通過配置這個選項來改變點擊的樣式
var router = new VueRouter({
mode:"history",
linkActiveClass:"active", //通過類名”active“來改變點擊樣式
routes:[
{
// ...
}
]
})