這是我參與8月更文挑戰的第8天,活動詳情查看:8月更文挑戰vue
vue-router官方文檔vue-router
<div id="app">
<h1>Hello App!</h1>
<p> <!-- 使用 router-link 組件來導航. --> <!-- 經過傳入 `to` 屬性指定連接. --> <!-- <router-link> 默認會被渲染成一個 `<a>` 標籤 --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這裏 --> <router-view></router-view> </div> // 定義路由 // 每一個路由應該映射一個組件。 其中"component" 能夠是 // 經過 Vue.extend() 建立的組件構造器, // 或者,只是一個組件配置對象。 // 咱們晚點再討論嵌套路由。 const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] // 建立 router 實例,而後傳 `routes` 配置 // 你還能夠傳別的配置參數, 不過先這麼簡單着吧。 const router = new VueRouter({ routes // (縮寫) 至關於 routes: routes }) 複製代碼
$route.params
// 1. 用name路徑的方式進行路由傳參
this.$router.push({ name: 'Goods', params: { goodsID: id } })
// 2. 用path路徑的方式進行路由傳參
this.$router.push({path:'goods',query:{goodsID:id}})
//接收this.$route.query.goodsID
複製代碼
vue- router默認hash模式, ur使用#後面定位路由,對seo不利,設置history,就可使用普通的url模式
history模式即普通url模式,這種模式充分利用history.pushState API來完成URL跳轉而無須從新加載頁面編程
const router = new VueRouter({
mode: 'history',
routes: [...]
})
複製代碼
能夠用來作用戶在沒有登陸註冊時的攔截
你可使用 router.beforeEach
註冊一個全局前置守衛:後端
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
複製代碼
每一個守衛方法接收三個參數:markdown
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應路由被 confirm 前調用
// 不!能!獲取組件實例 `this`
// 由於當守衛執行前,組件實例還沒被建立
},
beforeRouteUpdate (to, from, next) {
// 在當前路由改變,可是該組件被複用時調用
// 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
// 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。
// 能夠訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導航離開該組件的對應路由時調用
// 能夠訪問組件實例 `this`
}
}
複製代碼